MATLAB: While loop matrix problem

loopmatrix

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.

Best Answer

@galgool, before calling someone wrong please learn the language properly, in particular how if works when given a vector as an expression. From the doc:
An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false.
So, let's look at
if z5(i,:) < z5(i-1,:)
The expression is
z5(i,:) < z5(i-1,:)
The result of that expression is a logical vector (array of 0s and 1s). As per the rule above, the if is true only if all the elements of the vector are 1. I.e. the only time the expression is true is when z5(i, j) < z5(i-1, j) for all j. In general, you should avoid passing a vector to if because people don't know the rule above. The expression you've written is exactly equivalent to:
if all(z(5(i,;) < z5(i-1,:))
which is clearer.
As others have said, you will also have to loop over the columns.
Note that:
i = 2; %your code would error if you actually started at 1!
while i < constant
%some code that doesn't change i or the constant

i = i+1;
end
is more simply written as a for loop:
for i = 2:constant
%some code that doesn't change i or the constant
end
Note that if you didn't have the dependence on the previous c5 row, when z5(i,j) == z5(i-1, j), the whole thing could written without any loop at all.