0
votes

I have a matrix in Matlab(2012) with 3 columns and X number of rows, X is defined by the user, so varies each time. For this example though I will use a fixed 5x3 matrix.

So I would like to perform an iterative function on each row within the matrix, while the value in the third column is below a certain value. Then store the new values within the same matrix, so overwrite the original values.

The code below is a simplified version of the problem.

M=[-2 -5 -3 -2 -4]; %Vector containing random values

Vf_X=M+1; %Defining the first column of the matrix
Vf_Y=M+2; %Defining the secound column of the matrix
Vf_Z=M; %Defining the third column of the matrix

Vf=[Vf_X',Vf_Y',Vf_Z']; %Creating the matrix

while Vf(:,3)<0 
Vf=Vf+1;
end
disp(Vf)

The result I get is

 1     2     0
-2    -1    -3
 0     1    -1
 1     2     0
-1     0    -2

Ideally I would like to get this result instead

 1     2     0
 1     2     0
 1     2     0
 1     2     0
 1     2     0

The while will not start if any value is above zero to begin with and stops as soon as one value goes above zero.

I hope this makes sense and I have supplied enough information

Thank you for your time and help.

1
Why do you think you get this desire result (with this code), if the initial values on each column are different? - Adiel
Because I would like it to add a different amount to each row, so row 1 will have 2 added to it and row 2 will have 5 added to it. Does this make sense? - user2519890
@user2519890: for the simple addition in your example: why not do inds = Vf(:,3)<0; Vf(inds,:) = bsxfun(@minus, Vf(inds,:), Vf(inds,3));? - Rody Oldenhuis
Yes, it make sense. But your increment is on the whole matrix Vf, you need to evaluate the condition and the increment on each row separately. Look at Rody answer - Adiel
Adiel, yes that was my problem not knowing how to look at each row separately, I knew what the issue was but not the solution. Yes the solution Rody gave was just what i needed. Thank you though. - user2519890

1 Answers

0
votes

Your current problem is that you stop iterating the very moment any of the values in the third row break the condition. Correct me if I'm wrong, but what I think you want is to continue doing iterations on the remaining rows, until the conditions are broken by all third columns.

You could do that like this:

inds = true(size(Vf,1),1);
while any(inds)
    Vf(inds,:) = Vf(inds,:)+1;
    inds = Vf(:,3) < 0;
end

Of course, for the simple addition you provide, there is a better and faster way:

inds = Vf(:,3)<0; 
Vf(inds,:) = bsxfun(@minus, Vf(inds,:), Vf(inds,3));

But for general functions, the while above will do the trick.