writing a for loop that solves on two arrays at the same time

say I have this: x=1:5 y=1:5
I want to compute the for loop that multiplies x and y for every element of the two arrays, for example:
[x(1)*y(1), x(1)*y(2),x(1)*y(3), x(1)*y(4), x(1)*y(5)] as well as [x(2)*y(1), x(2)*y(2),x(2)*y31), x(2)*y(4), x(2)*y(5) ] and so forth.
The easy way out would be to write 5 separate for loops for each value of x for example x=1 y=1:5 for i=1:5 product=x*y(i) end
But I want to know how I could make just one for loop

Réponses (1)

x=1:5, y=1:5
solution
n = numel(y);
out = zeros(numel(x),n);
x1 = x.';
for i1 = 1:n
out(:,i1) = x1*y(i1);
end
without loop for..end
out = x(:)*y(:).';

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Tags

Question posée :

le 2 Déc 2011

Community Treasure Hunt

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

Start Hunting!

Translated by