Hi, I am new to MATLAB. I was trying to subtract the consecutive number in the series with the previous number and then storing this number to a new matrix. I implemented the following code but I need some help.

8 views (last 30 days)
I have a series num: 1
2
3
4
5
And I want the following series num2: 0
1
1
1
1
Below is my code:
len= length(num);
v=2;
j=1;
for i=i:len
num2{v,1} = minus (num{v,1},num{j,1});
v= v+1;
j=j+1;
end
  1 Comment
Guillaume
Guillaume on 1 Mar 2020
There are several issues with your loop:
  • matrix indexing uses () not {}, so it's num(v, 1), etc. Also since you're dealing with vectors you shouldn't be using 2D indexing. num(v) would do the same.
  • The start bound of your loop is wrong.
  • The v and j variables are completely pointless. j is always going to be the same as i and v is always going to be i+1. So your expression can be simplified to
num2(i+1) = num(i+1) - num(i)
Also note that I've replaced minus(..) by its more standard -, there's no point in making the code more obscure.
But.. see Thiago's answer for the proper way of doing this calculation in matlab.

Sign in to comment.

Answers (1)

Thiago Henrique Gomes Lobato
In Matlab what you want to do is a one line code, you should always try to vectorize your operations or use build in function, since loops are generally not so efficient:
num=[1:5]';
num2 = [0;diff(num)];
  1 Comment
Guillaume
Guillaume on 1 Mar 2020
Yes, despite what you may have been taught (unfortunately) loops are rarely an efficient solution in matlab. It usually forces you to write more code for no benefit. diff, as per Thiago's answer does exactly what you need. Another option is write the expression as the difference of two vectors:
num2 = [0; num(2:end) - num(1:end-1)];

Sign in to comment.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!