For loop not saving answers into matrix.

조회 수: 6 (최근 30일)
Claire
Claire 2013년 1월 9일
Hi all,
I'm sure I've done something silly, but I can't work out why my code isn't working. Hopefully a fresh pair of eyes will help.
I'm trying to perform a moving correlation by specifying the index locations within a matrix for the correlation to be performed on. This then cycles through the for loop to give me answers for my whole matrix.
BUT! It's not saving each value into my specified matrix, and my output (MIChinacorr) is just a NaN matrix.
I know that the corr code works, because when I manually say k=1, I get an answer.
What am I doing wrong?
%Select moving window
window_size=10; %for an 11 point window
%Perform Correlation
for k=2:389
MIChinacorr=NaN(401,1);
MIChinacorr(k,1)=
[corr(MI18Ocorr(k:k+window_size,1),China18Ocorr(k:k+window_size,1))];
end
Thanks for your help.

채택된 답변

Walter Roberson
Walter Roberson 2013년 1월 9일
Every iteration of the "for k" loop, you are assigning
MIChinacorr=NaN(401,1);
so you are overwriting all of MiChinacorr with NaN.
You should only initialize it once, before the loop.
  댓글 수: 1
Claire
Claire 2013년 1월 9일
That's it! I knew I was doing something silly, I just couldn't see it.
Thanks so much for your help. Claire.

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

추가 답변 (1개)

Roger Stafford
Roger Stafford 2013년 1월 9일
If you wrote the code just as you show it, you would need to add an ellipsis after the equal sign:
MIChinacorr(k,1)= ...

카테고리

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