is possible Array + Array but element by element without using loop ?

3 views (last 30 days)
Dear colleagues
I want to know if there is a command that allow to add array with another array but without using a loop, I want something like this .* but adding.
here i write an example:
X= [1 2 3]; Y=[4 5 6];
Z= X.+Y Z = [(1+4) (1+5) (1+6) (2+4) (2+5) (2+6) (3+4) (3+5) (3+6)]
Z = [5 6 7 6 7 8 7 8 9]
thank you for your help
  3 Comments
Star Strider
Star Strider on 10 Jul 2015
My code is as fast as MATLAB can be to do the calculations you want. Large vectors will take longer with any code, but bsxfun is the fastest function for what you want to do.
If you want to do comparisons on the run times between various ways to do the calculations, use the timeit function.

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 10 Jul 2015
This works:
X = [1 2 3];
Y = [4 5 6];
Z = reshape( bsxfun(@plus, X, Y'), 1, []);
  3 Comments
Jorge  Peñaloza Giraldo
Jorge Peñaloza Giraldo on 10 Jul 2015
Edited: Star Strider on 10 Jul 2015
What do you thing about this:
ones(3,1)*[1 2 3]+[4 5 6]'*ones(1,3)
function s=sumavec(v1,v2)
n=size(v1,3);
s=ones(n,1)*v1+v2'*ones(1,n);
which is better about computing velocity ??
Star Strider
Star Strider on 10 Jul 2015
My pleasure.
The bsxfun call returned a matrix, but since you want a row vector, I used the reshape function to create a vector out of it.
The bsxfun code would likely be much faster than a loop.
This will not give you any useful information:
n=size(v1,3);
because your arguments are vectors, not 3-dimensional matrices, so ‘n’ will always be 1, and the ‘s’ assignment will throw a ‘Matrix dimensions must agree.’ error when you attempt the addition. For vector arguments:
n = length(v1);
is likely sufficient, depending on what you want to do.
That problem corrected, your ‘s’ assignment will return the same matrix bsxfun produced, so you would still have to reshape it to get your vector returned as ‘s’:
s = s(:)';
would work. This creates a column vector from ‘s’ and then transposes it to create your row vector. I considered this, but decided to code it in one line, and reshape allowed me to do that.
You can create an anonymous function out of my code easily enough:
sumavec = @(v1, v2) reshape( bsxfun(@plus, v1(:)', v2(:)), 1, []);
This will produce your row vector, without regard to ‘v1’ and ‘v2’ being row or column vectors, since it forces them both to be column vectors and then does the appropriate operations.

Sign in to comment.

More Answers (1)

Jorge  Peñaloza Giraldo
Jorge Peñaloza Giraldo on 10 Jul 2015
Thank you for all.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!