while loop matrix problem
이전 댓글 표시
hi,
I want to use a while loop on matrices, to define a new matrix by calculating one row each time.
I'm trying to do it without creating another loop that will go over the columns. Is that possible?
for example:
z5 and k5 are known matrices. This loop defines c5.
i=1;
while i<imax
if z5(i,:) < z5(i-1,:)
c5(i,:) = k5(i,:);
elseif z5(i,:) > z5(i-1,:)
c5(i,:) = z5(i,:);
else
c5(i,:) = c5(i-1,:);
end
i=i+1;
end
It's not doing what I want it to do and I'm not sure what exactly its doing.
Would appreciate any help and clarification on this matter.
댓글 수: 10
Torsten
2019년 7월 26일
result = z5(i,:) < z5(i-1,:)
is not the same as
for j=1:size(z5,2)
result(j) = z5(i,j) < z5(i-1,j)
end
Test it and see the difference.
Galgool
2019년 7월 26일
Bob Thompson
2019년 7월 26일
편집: Bob Thompson
2019년 7월 26일
if z5(i,:) < z5(i-1,:)
How is this evaluated for each row?
A = [1 2 3;
4 2 1];
It could be argued that the second row of A is greater than the first, because the sum total of the elements is greater than the first row. It could also be argued that the second row is not greater because each individual element is not greater than the corresponding element in the first row.
An inequality comparison statement is really only useful for comparing one piece of information with another. If you would like to complete all of these comparisons at once, and don't want to use a loop, you can use & to have multiple comparisons for one if statement, but this is very tedious for a large z5 matrix.
if z5(i,1) < z5(i-1,1) & z5(i,2) < z5(i-1,2)
Torsten
2019년 7월 26일
As you can see from our answers, it's not possible without looping because comparisons must be done elementwise to get the results you expect to get.
Galgool
2019년 7월 26일
If you test
if z5(i,:) < z5(i-1,:)
the result will be true only if the vector v = z5(i,:) < z5(i-1,:) is a vector of ones at all positions.
So if there is only one case for which z5(i,j) >= z5(i-1,j), all other cases for which z5(i,:) < z5(i-1,:) are ignored, positions for which you intend to set c5(i,:) = k5(i,:), I guess.
Maybe this is what you want to do:
jdx1 = z5(i,:) < z5(i-1,:);
jdx2 = z5(i,:) > z5(i-1,:);
jdx3 = z5(i,:) == z5(i-1,:);
c5(i,jdx1) = k5(i,jdx1);
c5(i,jdx2) = z5(i,jdx2);
c5(i,jdx3) = c5(i-1,jdx3);
Galgool
2019년 7월 26일
the cyclist
2019년 7월 26일
편집: the cyclist
2019년 7월 26일
To reiterate what Torsten is saying ...
To enter an if statement on a vector condition, all elements of that vector have to evaluate to true. MATLAB doesn't discern the if condition element-by-element.
That is the fatal flaw in your algorithm
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 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!

