Can I use a for loop "elementwise" for a given vector?
Show older comments
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.
Accepted Answer
More Answers (1)
Walter Roberson
on 29 Apr 2018
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.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!