Eghbal
Eghbal

Reputation: 3783

Subtract any number from previous number in MATLAB

Suppose that we have this matrix in MATLAB:

a = [1,3,3,4,6];

I want subtract any number from previous number so we have a_out as output:

a_out = [1,2,0,1,2];

How can I do this without using loop?

Upvotes: 2

Views: 139

Answers (2)

bni i
bni i

Reputation: 113

a = [1,3,3,4,6];

a_out = [a 0] - [0 a];
a_out = a_out(1:end-1);

Upvotes: 1

Ander Biguri
Ander Biguri

Reputation: 35525

You want diff([0 a]).

diff computes the "Differences and Approximate Derivatives", and as you also want the difference between 0 and your first element, you need to concatenate a 0 to your vector.

Upvotes: 9

Related Questions