MATLAB Answers

0

How to subtracts elements in a list

Asked by Rishi Kiran Shankar on 28 Jun 2019
Latest activity Commented on by Star Strider
on 3 Jul 2019
I have list like;
A = [x1,x2,x3,x4];
i want a list which can subtract first element with all other element and so on.\
i need results like [x1-x2,x1-x3,x1-x4,x2-x3,x2-x4,x3-x4]
Any help would be appreciable.
Thanks in advance

  0 Comments

Sign in to comment.

2 Answers

Answer by Star Strider
on 28 Jun 2019
Edited by Star Strider
on 28 Jun 2019
 Accepted Answer

To get a vector output:
A = randi(9, 1, 4) % Create Vector
Dif = A(:) - A(:)'; % R2016b & Since
Dif = bsxfun(@minus, A(:), A(:)'); % R2016a & Previous
Out = (triu(Dif)+tril(nan(size(Dif))))';
Out = Out(~isnan(Out))'
so for example:
A =
8 9 7 2
Out =
-1 1 6 2 7 5
EDIT — Corrected comments. Code unchanged.

  5 Comments

You can switch them back, and we can delete these comments. No one will ever know. ;-)
Hi Star Strider. Thanks a lot!
As always, my pleasure!

Sign in to comment.


Answer by Matt J
on 28 Jun 2019

A(:)-A(:).'

  0 Comments

Sign in to comment.