MATLAB Answers

John Doe
0

Finding the difference between columns in matrix without loops

Asked by John Doe
on 11 May 2013
Accepted Answer by Matt J

I have the results from an iterative process, where the results from each iteration is placed beside eachother, like this:

res = 
   43.7826   38.8460   38.6889   38.6912   38.6915
  107.0735   98.5577   98.1212   98.1170   98.1175
 -134.6218 -131.6938 -131.5378 -131.5352 -131.5352
 -105.9498 -103.1403 -102.9195 -102.9139 -102.9139

What I want to do is create one matrix that shows the difference between each column, and one matrix that shows the percentage change from one column to the next.

Edit: The first column of the first matrix will be:

diff(:,1) = res(:,2)-res(:,1);

Similar for the second matrix, but there I want the percentage change. This is obviously simple to do using loops, but is there a clever way to do this without loops (maybe using some built-in Matlab functions)?

Thanks.

  2 Comments

... difference between each column ... what exactly does that mean?

The first column of the first matrix will be

diff(:,1) = res(:,2)-res(:,1);

Similar for the second matrix, but in that one I want the percentage change.

Products

No products are associated with this question.

1 Answer

Answer by Matt J
on 11 May 2013
 Accepted answer

 firstmatrix=diff(res,1,2);
 secondmatrix=100*bsxfun(@rdivide,firstmatrix,res(:,1:end-1));

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!