Can I use a for loop "elementwise" for a given vector?

조회 수: 3 (최근 30일)
Nick Thomas
Nick Thomas 2018년 4월 29일
답변: Stephen23 2018년 4월 29일
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.

채택된 답변

Stephen23
Stephen23 2018년 4월 29일
The for operator operates over the columns of its input argument, so in your first example you provide it with one single column it will iterate exactly once and the loop iterator will be that column. In your second example you provide for with a row vector, and so each column is one scalar value.
You can fix the first example by converting it to a row vector:
for k = x30(:).'
A(k,k) = -4;
...
end

추가 답변 (1개)

Walter Roberson
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by