How do I access array elements in for loop?

9 ビュー (過去 30 日間)
Deen Halis
Deen Halis 2015 年 9 月 28 日
コメント済み: Deen Halis 2015 年 9 月 29 日
How do I access array elements in for loop? Below is what I tried but had error. Any suggestion is appreciated.
Halis
K = [2 5];
for i = 1:2;
K(i) = K(1,i);
B(i) = 2*K(i);
C = 4*B(i);
disp(C);
D = C(1,1)
E = C(1,2)%error:Attempted to access C(1,2); index out of bounds because numel(C)=1.
F = 3*D^2 + 4*E^2
G = 3*D*E + 4*D*E
end
  2 件のコメント
Jan
Jan 2015 年 9 月 29 日
The line K(i) = K(1,i) is meaningles. Simply omit it, because it replaces the i'th element of K by the i'th one. This would only have an effect if K is a matrix or a multidimensional array.
D,E,F,G are overwritten in each iteration. Is this your intention?
Deen Halis
Deen Halis 2015 年 9 月 29 日
Thanks, I have made the changes as u suggested. D,E,F,G are not overwritten.I wish to access the values of each iterate to get D(=4) and E (=10) to enable me calculate F and G.
K = [2 5]; for i = 1:2; B(i) = 2*K(i); disp(B(i)); %Now i want to access the values of B(i) separately, ie 4 and 10, %making D = 4 and E = 10
%% Then I can determine F and G % F = 3*D^2 + 4*E^2 % G = 3*D*E + 4*D*E end

サインインしてコメントする。

採用された回答

Thorsten
Thorsten 2015 年 9 月 29 日
K = [2 5];
for i = 1:2; B(i) = 2*K(i); end
D = B(1)
E = B(2)
F = 3*D^2 + 4*E^2
G = 3*D*E + 4*D*E
This could be simplified to
K = [2 5];
B = 2*K;
F = [3 4]*B.^2'; % == 3*B(1)^2 + 4*B(2)^2
G = 7*prod(B); % == 3*prod(B) + 4*prod(B);
  1 件のコメント
Deen Halis
Deen Halis 2015 年 9 月 29 日
Thanks! This worked!. Thanks to everyone that has helped.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by