Can I use a vector as index variable for a loop?
63 ビュー (過去 30 日間)
古いコメントを表示
Hello, I have a question about the for loop. Why isn't it possible to use an element of a vector as the index variable?
Here is an example:
i_max=[3;2;4];
n=size(i_max,1);
i=zeros(n);
j=1;
for i(2)=0:1:i_max(1)
A(:,j)=i
j=j+1
end
Everytime I try this I get the error message "Unbalanced or unexpected parenthesis or bracket."
Is there any other way I can use the vector "i(x)" as index variable? I don't want to define a new variable like:
i_new=i(2)
This wouldn't really help me since my code must be very dynamic.
Thanks.
0 件のコメント
回答 (2 件)
michael
2016 年 10 月 3 日
You have to think MATLAB.
Your code is messy and hard to read.
i_max=[3;2;4]; <== column vector of size 1x3
n=size(i_max,1); <== you can use length instead of size
i=zeros(n); <=== i is 3x3 matrix of zeros
j=1;
for i(2)=0:1:i_max(1) if you would like to update the i matrix, do it in the loop. This statement is illegal
A(:,j)=i <== you can't assign matrix to vector
j=j+1
end
I'd suggest to set your requirements of the code. if you would like to use array of indexes, you can do it like that:
i=(1:10)*2
idx=[1,3,6]
i(idx)
ans =
2 6 12
example for the for loop:
for n = 1:40
r(n) = rank(magic(n));
end
2 件のコメント
michael
2016 年 10 月 3 日
if you would like to have a zero matrix of the same size as i_max
i=zeros(size(i_max))
Joe Yeh
2016 年 10 月 3 日
Well, you can't use loop variable that way. You can use nested for loop to assign new loop variable for the inner for loop. For example :
i_max=[3;2;4];
n=size(i_max,1);
i=zeros(n);
j=1;
for x = 1:length(i)
ii = i(x);
for ii = 0:1:i_max(1)
A(:,j)= ii;
j=j+1;
end
end
Note, however, that nested for loop is usually slow. You should try to vectorize your code. I can provide you with further example if you define more clearly what your programming problem is.
4 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!