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
답변 (1개)
Andrei Bobrov
2011년 12월 2일
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(:).';
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!