rcty
rcty

Reputation: 737

substract one element of NX1 matrix with another

I have the following nX1 matrix, here n is very large, I want to carry out the following operation- (2nd term) minus (first term) ,that is (2.25555-1.45656),(4.74096-2.25555),(440.0000-4.74096) and so on.... for the remaining 'n' number of rows

1.45656
2.25555
4.74096
440.00000
0.02000
550.7
0.268

I have done the following, but it is giving only one value

[n,m]=size(a)
for i=1,n
    delta_g12(i)=(g_12(i+1)-g_12(i));
end

Upvotes: 2

Views: 100

Answers (1)

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

The easiest, Matlab-like way is using a built-in function called diff:

 delta_g12 = diff(g_12);

But your way is also possible. Your code is almost correct, the error is in the first line:

  for i=1,n

The interpreter ignores the ,n and acts as if you wrote:

  for i=1

Instead, you should use the colon operator:

[n,m]=size(a)
for i=1:n
    delta_g12(i)=(g_12(i+1)-g_12(i));
end

Upvotes: 5

Related Questions