UpperEastSide
UpperEastSide

Reputation: 137

Finding the difference between one index and the remaining indices

I have a vector:

A = [1 2 3 4 5];

I want to find the difference between A(1) and the remaining indices:

A(1) = 1; 1 - A = [0 -1 -2 -3 -4]

I then want to continue to A(2) and until the end of the vector. So that I have the differences between all points from each other.

At the moment I use loops but it is very time consuming. How can I do this using vectorization techniques to improve performance?

I'm using MATLAB 2016a

Upvotes: 1

Views: 68

Answers (1)

beaker
beaker

Reputation: 16791

If you're using 2016a or earlier, you'll want to use bsxfun:

>> A = [1 2 3 4 5];
>> bsxfun(@minus, A.', A)
ans =

   0  -1  -2  -3  -4
   1   0  -1  -2  -3
   2   1   0  -1  -2
   3   2   1   0  -1
   4   3   2   1   0

Starting in 2016b (or in Octave), you can take advantage of implicit expansion and do away with bsxfun:

>> A.' - A
ans =

   0  -1  -2  -3  -4
   1   0  -1  -2  -3
   2   1   0  -1  -2
   3   2   1   0  -1
   4   3   2   1   0

Upvotes: 7

Related Questions