while loop matrix problem
Show older comments
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 Comments
Torsten
on 26 Jul 2019
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
on 26 Jul 2019
Bob Thompson
on 26 Jul 2019
Edited: Bob Thompson
on 26 Jul 2019
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
on 26 Jul 2019
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
on 26 Jul 2019
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
on 26 Jul 2019
the cyclist
on 26 Jul 2019
Edited: the cyclist
on 26 Jul 2019
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
Accepted Answer
More Answers (0)
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!
