MATLAB Answers

Subtraction between the rows of matrix

226 views (last 30 days)
I have a matrix A which is 880x100 and I want to do the subtraction between row to row.
For example
A= [ 1 1 1 1 ;2 2 2 2 ;.......880 880 880 880];
I want to take row 1- row 22, 2-21, ... row 11 -row 12, then row 12-row 33, row 13-row 32,.. row 22-row 23,
then row 23-row 44, ...row 34-row 55. The sum of row number minus other rows in the first 11 subtractions is 23 such as 22+1, 2+21. However, starting from row 12 - then the sum is 45 which is adding 22 to the 23, and then starting from 33 the sum is 67 which is 45+22, so on.
I was successfully doing for the first 11 but it is no longer valid after that.
for i =1:880
A(i,:)-A(23-i,:);
end
Anybody has an idea how to do this. Thanks.

  2 Comments

Stephen Cobeldick
Stephen Cobeldick on 1 Mar 2015
Currently each row of A contains the same repeated value... is this actually the case, or do the rows contain different values?
Laura
Laura on 1 Mar 2015
They are different decimal numbers and it has dimension of 880 x 100 not 4 column as shown above.

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 1 Mar 2015
Edited: Stephen Cobeldick on 2 Mar 2015
Why do this in a loop when you can utilize MATLAB's ability to vectorize operations. This means you can simply perform all subtractions simultaneously, in which case all that is required is to specify the indices of the rows that you want to subtract:
A = repmat((1:880).',1,4);
X = reshape(flipud(reshape(12:size(A,1),11,[])),[],1);
Y = 1:numel(X);
B = A(Y,:) - A(X,:);
The vector X contains the indices of all subtrahends, while Y is the indices of all minuends. The array B is the output, and it works for any number of columns of A.
Explanation: if you write out (in a column) all of the minuend indices, you will find that they are simply the positive integers 1,2,3,4,5,6,..... Likewise the subtrahend indices are every group of eleven integers, starting from twelve, reversed within every group. If you look at X and Y this is what you will see. And so we can generate these indices very easily, and perform all of the subtractions in one go.
PS: this is an interesting coincidence, two people trying to solve the same problem on the same weekend:

  0 Comments

Sign in to comment.

More Answers (1)

michael scheinfeild
michael scheinfeild on 26 Feb 2015
just prepare the row index before as example :
a=[ 1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]
a =
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
>>
c=[1 2]; d=[3 4]
d =
3 4
>> x=a(c,:)-a(d,:)
x =
-8 -8 -8 -8
-8 -8 -8 -8

  1 Comment

Laura
Laura on 1 Mar 2015
This is for short matrix where you can define what is c and d.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!