Can I use a for loop "elementwise" for a given vector?
显示 更早的评论
I've got a vector that I'd like to use with the "for" statement in a for loop. Within the loop I'm filling in a matrix based on its coordinates. Something like this.
x31 = x30(:);
for x31 = x31
A(x31,x31) = -4;
A(x31,x31+1) = 1;
A(x31,x31-nb) = 1;
A(x31,x31+nb) = 1;
A(x31,x31-1) = 1;
end
x31 is a pretty long vector that has some skips in the numbers (it's not consecutive). A is a huge matrix. The problem I'm getting is that it seems it's not running through the loop with just one x31 value at a time... if that makes any sense. For example, if two values of x31 were 200 and 300, it'd be making A(200,300-1)=1, when I just want A(200,200-1)=1 and A(300,300-1)=1. Basically it's changing way more values of my A matrix than I'm intending to.
When I have made for loops in the past where the incrementing is done within the loop, like this:
a=1
b=20
for x31 = a:b
A(x31,x31) = -4;
A(x31,x31+1) = 1;
A(x31,x31-nb) = 1;
A(x31,x31+nb) = 1;
A(x31,x31-1) = 1;
end
I've had no problems, it doesn't "mix" the values. How can I get this to happen in the first case? Apologies for not being able to get the code formatting to work.
采纳的回答
更多回答(1 个)
Walter Roberson
2018-4-29
When you have
for variable = expression
then variable is set to each column of the expression in turn. for variable = a:b creates a row vector a:b and the columns of the row vector are the individual values, a, a+1, a+2... b. By you have x31 = x30(:) which is a column vector, so the first column if it is the entire vector.
类别
在 帮助中心 和 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!