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!

