Kelly
Kelly

Reputation: 87

Subtract element from row above to create new row (Matlab)

I have a matrix like the following:

A =

 5     2    10    14    11

I am looking to create an additional row using this data. The element in the fifth column, second row, is constant and known: 100

By subtracting from the above row I am looking to insert these values

B =

63    65    75    89   100

E.g. 100-11 = 89. 89-14=75

To ultimately give the following:

[A;B]

ans =

 5     2    10    14    11
63    65    75    89   100

Any suggestions?

Upvotes: 3

Views: 177

Answers (2)

Colin T Bowers
Colin T Bowers

Reputation: 18530

I believe what you are after is this:

A = [5, 2, 10, 14, 11];
Soln = [A; 100 * ones(1, length(A))];
Soln(2, 1:end - 1) = 100 - fliplr(cumsum(fliplr(A(2:end))));

EDIT: Probably go with cjh's solution (+1 for it). It requires one less call to fliplr so is probably faster.

Upvotes: 3

cjh
cjh

Reputation: 866

You can use the cumulative summation of the elements of A, via the MATLAB function cumsum, in order to perform this calculation:

knownvalue = 100; 
firstrow = [5     2    10    14    11]
secondrow = fliplr(knownvalue  - cumsum([0 firstrow(end:-1:2)]))

Upvotes: 6

Related Questions