how to save each loop data

조회 수: 12 (최근 30일)
abdul asad
abdul asad 2016년 6월 11일
댓글: Afraz MEHMOOD CHAUDHRY 2022년 1월 28일
I have a for loop, but every iteration overwrites the variable and I have only the final data left..
where p is an array p=[1:1:20]' how can I save data from every loop saves only the last value when 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 . how do I get the other values?

답변 (1개)

Chad Greene
Chad Greene 2016년 6월 11일
편집: Chad Greene 2016년 6월 11일
There are several ways to do this. One way is to make a counter, and increment that counter each time through the loop:
p=[1:1:20]';
k = 0; % <-start a counter
for x=.1:.1:1
k=k+1; % <-increment the counter
q(:,k)=x.*p; % <- log the result
end
Another way is very similar, but some would say better coding style:
p=[1:1:20]';
x=.1:.1:1;
for k = 1:length(x)
q(:,k) = x(k).*p;
end
Or of course if all you need is the cross product you can skip the loops altogether:
p=[1:1:20]';
x=.1:.1:1;
q = p*x;
  댓글 수: 2
abdul asad
abdul asad 2016년 6월 11일
it works... thanks for your help
Afraz MEHMOOD CHAUDHRY
Afraz MEHMOOD CHAUDHRY 2022년 1월 28일
for me second option worked easily. Thanks Chad!

댓글을 달려면 로그인하십시오.

카테고리

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