3

Possible Duplicate:
MATLAB: Matrix of differences

I am not sure how to word this question but I will do my best:

I have two vectors, A and B.

I want to subtract the all values in A by every individual value of B.

For example, all values in A are subtracted by the first value of B. Then the all values of A are subtracted by the second value of B, and so on.

The resultant matrix should be length(A) x length(B) and look something like this:

Ans = [A - B(1); A - B(2); A - B(3); ....... ]

Is there any way of doing this without a loop?

Community
  • 1
  • 1
gtdevel
  • 1,513
  • 6
  • 21
  • 38
  • The linked duplicate is subtracting `A` from `A`. Subtracting `B` from `A` should be easy to figure out. – Jonas Nov 17 '12 at 14:31
  • 1
    Yesterday I answered *Exactly* to the same question putting effort in it. [Here](http://stackoverflow.com/a/13422675/1714661). – Acorbe Nov 17 '12 at 17:17

2 Answers2

3

The line like @Memming and @Jonas says:

Result = bsxfun(@minus, a, b');
Barney Szabolcs
  • 11,846
  • 12
  • 66
  • 91
2
a=[2 3 4];      %first take two vector a and b of any size
b=[5 6 5 7];
m=size(a);      % Then Calculate the size of the vectors
n=size(b);  
r1=a'*ones(n);  % replicate the vector a and b one can use **repmat** here for replication  
r2=ones(m)'*b;  % like **repmat(a',n)  &  repmat(b,m(end),1)**
Result=r1-r2

Result =

    -3    -4    -3    -5
    -2    -3    -2    -4
    -1    -2    -1    -3
Gunther Struyf
  • 11,158
  • 2
  • 34
  • 58
veeresh
  • 69
  • 2