Can I use a vector as index variable for a loop?
显示 更早的评论
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.
回答(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 个评论
Rene Stiller
2016-10-3
编辑:Rene Stiller
2016-10-3
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 个评论
Rene Stiller
2016-10-3
编辑:Rene Stiller
2016-10-3
are you familiar with binary numbers? it is same idea:
0=000
1=001
2=010
3=011
4=100
5=101
6=110
7=111
I think you can do it with single for loop (or at most 2 for loops):
1 pass: go over all numbers. if there are more numbers, just copy the data x times where x is count of 0 to v(2)
2 pass: do the same, but each time write each number x times, where x is the v(2). if there are more numbers, just copy the data x times where x is count of 0 to v(3)
3 pass: do the same, but each time write each number x times, where x is the v(3). if there are more numbers, just copy the data x times where x is count of 0 to v(4)
...
I hope that this algo would be fine, but may have some wrong statements. please use it as guideline.
Try to think about your code before you write it.
Rene Stiller
2016-10-3
Rene Stiller
2016-10-4
类别
在 帮助中心 和 File Exchange 中查找有关 Surrogate Optimization 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!