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

조회 수: 12 (최근 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
Jorge  Peñaloza Giraldo
Jorge Peñaloza Giraldo 2015년 7월 10일
i need the code too fast. I will work with array very big
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
Jorge Peñaloza Giraldo 2015년 7월 10일
편집: 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
Jorge Peñaloza Giraldo 2015년 7월 10일
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