writing a for loop that solves on two arrays at the same time
Show older comments
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
Answers (1)
Andrei Bobrov
on 2 Dec 2011
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(:).';
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!