For loop index assistance

1 view (last 30 days)
Dominic Piedmont
Dominic Piedmont on 13 Jul 2019
Answered: Star Strider on 13 Jul 2019
I have these nested for loops. I'm trying to output these delta_K_estimate values but it keeps populating with the same values from 1:101, 102:202, 203:303, etc. Each value across all columns should vary and be different from the previous. I'm sure it's some small index error that i'm missing but can't see. Thanks in advance for you help!
P=zeros(length(transpose(K_hat)),2);
delta_K_estimate=zeros(82,505);
for i=0:number_of_peaks-1 %each peak
for j=(101*i)+1:(101*i)+101 %each C_avg
P(j,:)=polyfit(K_hat(:,j),delta_K(:,i+1),1); %determination of linear fit equation
delta_K_estimate(:,j)=P(j,1).*K_hat(:,j)+P(j,2); %linear fit estimate of delta_K
end
end
  3 Comments
Dominic Piedmont
Dominic Piedmont on 13 Jul 2019
I don't think that's really necessary for answering a syntax/indexing error. I'm sure random data will suffice.
dpb
dpb on 13 Jul 2019
Edited: dpb on 13 Jul 2019
Well, knowing the sizes would certainly help even w/o specific data to be able to try to read the code without making up stuff.
NB:
P=zeros(length(transpose(K_hat)),2);
length(X) is defined as max(size(X)) so you may, or may not, have the result there that is expected. Use the proper size() dimension argument needed to ensure robust code.
delta_K_estimate(:,j)=polyval(P(j,:),K_hat(:,j)); %linear fit estimate of delta_K

Sign in to comment.

Answers (1)

Star Strider
Star Strider on 13 Jul 2019
I do not understand the reason you are indexing ‘j’ as a for loop.
I would do something like this to get consecutive ‘j’ vectors of length 100, beginning at 1, 101, 201, 301, ...
for i=1:number_of_peaks %each peak
j = (1:100)+100*(i-1);
P(j,:)=polyfit(K_hat(:,j),delta_K(:,i+1),1); %determination of linear fit equation
delta_K_estimate(:,j)=P(j,1).*K_hat(:,j)+P(j,2); %linear fit estimate of delta_K
end

Categories

Find more on Statistics and Machine Learning Toolbox 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!