how to save output of for loop

조회 수: 1 (최근 30일)
Safi ullah
Safi ullah 2017년 2월 28일
답변: MARCO FORTI 2019년 10월 25일
Hi, I have a matrix A=54×100. For some specific condition I perform an operation on each row of “A” with the help of for loop. now I need to save the output of this for loop. I tried like
S=zeros(54,100);
for i=1:54;
Ri=A(i,:);
answer=mean(reshape(Ri,5,20),1);
S(i)=answer;
end
but not succeed.

채택된 답변

Alexandra Harkai
Alexandra Harkai 2017년 2월 28일
The size of output S in this case will be 54*20. To specify that you want to assign answer to the whole row of S, use the same (i,:) indexing you used for A:
S=zeros(54,20);
for i=1:54;
Ri=A(i,:);
answer=mean(reshape(Ri,5,20),1);
S(i,:)=answer;
end
  댓글 수: 2
Safi ullah
Safi ullah 2017년 2월 28일
@ Alexandra Harkai thanks,now the code work well.
Jan
Jan 2017년 2월 28일
+1, correct.

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

추가 답변 (2개)

Jan
Jan 2017년 2월 28일
This works without a loop also:
S = squeeze(mean(reshape(Ri, size(A, 1), 5, 20), 2));
  댓글 수: 1
Alexandra Harkai
Alexandra Harkai 2017년 2월 28일
+1 for teaching me squeeze

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


MARCO FORTI
MARCO FORTI 2019년 10월 25일
Hello all,
I am doing forecasting and the algorithm works fine, nevertheless I can not save the output as I would.
In particular, the final loop is:
%final forecast
ff=zeros(horiz,1);
for i=1:horiz
xf=xb(1:end-i+1,:);
yf=yb(i:end);
betah=(xf'*xf)\(xf'*yf);
ff(i)=y(end-pbest+1:end)'*betah;
th=[th;ff(i)]; %
end
In this I only get the general output as "ans", while I would get the two vector "ff" and "th" both in sequence (as "ans" reports) and separately.
Can anyone help me?

카테고리

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