is possible Array + Array but element by element without using loop ?
11 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Jorge Peñaloza Giraldo
le 10 Juil 2015
Commenté : Star Strider
le 10 Juil 2015
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 commentaires
Star Strider
le 10 Juil 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.
Réponse acceptée
Star Strider
le 10 Juil 2015
This works:
X = [1 2 3];
Y = [4 5 6];
Z = reshape( bsxfun(@plus, X, Y'), 1, []);
3 commentaires
Jorge Peñaloza Giraldo
le 10 Juil 2015
Modifié(e) : Star Strider
le 10 Juil 2015
Star Strider
le 10 Juil 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.
Plus de réponses (1)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!