Reputation: 69
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.
Upvotes: 1
Views: 99
Reputation: 221584
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
Upvotes: 3
Reputation: 112699
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).'));
Upvotes: 1
Reputation: 238309
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);
Upvotes: 0