1

Say I have two vectors: X=[x0,x1,x2]; Y=[y0,y1]; does there exist a single command in Matlab that I can generate a 2x3 matrix Z=f(X,Y), where Z=[x0+y0, x1+y0, x2+y0; x0+y1, x1+y1, x2+y1]?

Thanks in advance.

Divakar
  • 218,885
  • 19
  • 262
  • 358
hookch
  • 69
  • 1
  • 1
  • 10

4 Answers4

3

It's a perfect case for bsxfun[C = bsxfun(fun,A,B) applies the element-by-element binary operation specified by the function handle fun to arrays A and B, with singleton expansion enabled. In this case, @plus is the function handle needed.] -

Z = bsxfun(@plus,X,Y.')

As an example, look at this -

X=[2,3,5]
Y=[1,4]
Z = bsxfun(@plus,X,Y.')

which gives the output -

X =
     2     3     5
Y =
     1     4
Z =
     3     4     6
     6     7     9
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • +1 Just watch out that `'` will alter the result (complex conjugate) if vectors are complex – Luis Mendo Jun 25 '14 at 09:19
  • @LuisMendo Yes! In this case I must use `.`, because OP has symbols - `x0`, `y0`, so one mustn't take chances :) Thanks! – Divakar Jun 25 '14 at 09:20
1

try this

Z = repmat(X,numel(Y),1) + repmat(Y',1,numel(X));
Nishant
  • 2,571
  • 1
  • 17
  • 29
1

You can also use ndgrid:

[xx yy] = ndgrid(Y,X);
Z = xx+yy;

And there's the possibility to abuse kron as follows (but note that internally kron basically uses a variation of ndgrid):

Z = log(kron(exp(X),exp(Y).'));
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
0

Alternative to Nishant anwser would be using kron:

   %for example
   X=[1,2,3]; Y=[1,2]
   Z = kron(X, ones(numel(Y), 1)) +  kron(ones(1, numel(X)), Y'); 

Z =

     2     3     4
     3     4     5

If this would suit you, you could define a function:

% skron for sum kron
skron = @(X,Y) kron(X, ones(numel(Y), 1)) +  kron(ones(1, numel(X)), Y');

Z = skron(X,Y);
Marcin
  • 215,873
  • 14
  • 235
  • 294