Asked by Jakub Nosek
on 21 Oct 2017

Hello,

I have a matrix and I need to subtract every element from each other in each row. So, for example, if I have a matrix A=[1 2 3; 4 8 9] the result should be for example this B=[1 2 1; 4 5 1] - the sequence is not important. But I need to know that the result in the matrix B corresponds to a particular elements' subtraction in matrix A. So if I have for example a subtraction of 2-1, which is A(1,2)-A(1,1) in matrix A and the result is 1 in matrix B I need to know that 1 corresponds to A(1,2)-A(1,1) and keep track of it.

I have tried to do it with cycles and also with a "bsxfun" function but unfortunately can't get the correct result.

g=[1 3 8; 4 6 2];

[u,v]=size(g);

for i=1:u

for j=1:v

a(i,j)=bsxfun(@minus,g(i,j),g(i,j)');

end

end

I'll be glad if anyone can help me. Thanks

Answer by Roger Stafford
on 21 Oct 2017

Accepted Answer

You don't need a for-loop.

C = nchoosek(1:size(A,2),2);

B = A(:,C(:,2))-A(:,C(:,1));

Opportunities for recent engineering grads.

Apply Today
## 4 Comments

## KL (view profile)

Direct link to this comment:https://ch.mathworks.com/matlabcentral/answers/362469-how-to-subtract-elements-in-a-matrix#comment_495504

## Jakub Nosek (view profile)

Direct link to this comment:https://ch.mathworks.com/matlabcentral/answers/362469-how-to-subtract-elements-in-a-matrix#comment_495505

## KL (view profile)

Direct link to this comment:https://ch.mathworks.com/matlabcentral/answers/362469-how-to-subtract-elements-in-a-matrix#comment_495506

## Jakub Nosek (view profile)

Direct link to this comment:https://ch.mathworks.com/matlabcentral/answers/362469-how-to-subtract-elements-in-a-matrix#comment_495513

Sign in to comment.