Can I use a vector as index variable for a loop?
46 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (2)
michael
le 3 Oct 2016
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 commentaires
michael
le 3 Oct 2016
if you would like to have a zero matrix of the same size as i_max
i=zeros(size(i_max))
Joe Yeh
le 3 Oct 2016
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 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!