Subtraction between the rows of matrix

조회 수: 69 (최근 30일)
Laura
Laura 2015년 2월 26일
편집: Stephen23 2015년 3월 2일
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
Stephen23
Stephen23 2015년 3월 1일
편집: Stephen23 2015년 3월 1일
Currently each row of A contains the same repeated value... is this actually the case, or do the rows contain different values?
Laura
Laura 2015년 3월 1일
They are different decimal numbers and it has dimension of 880 x 100 not 4 column as shown above.

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2015년 3월 1일
편집: Stephen23 2015년 3월 2일
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:

추가 답변 (1개)

michael scheinfeild
michael scheinfeild 2015년 2월 26일
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
Laura
Laura 2015년 3월 1일
This is for short matrix where you can define what is c and d.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by