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

9 次查看(过去 30 天)
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 个评论
Star Strider
Star Strider 2015-7-10
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.

请先登录,再进行评论。

采纳的回答

Star Strider
Star Strider 2015-7-10
This works:
X = [1 2 3];
Y = [4 5 6];
Z = reshape( bsxfun(@plus, X, Y'), 1, []);
  3 个评论
Jorge  Peñaloza Giraldo
编辑:Star Strider 2015-7-10
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 2015-7-10
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.

请先登录,再进行评论。

更多回答(1 个)

Jorge  Peñaloza Giraldo
Thank you for all.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by