Problem with for loop and polyfit

조회 수: 1(최근 30일)
lena kappa
lena kappa 2022년 4월 11일
편집: lena kappa 2022년 4월 12일
Hello everyone, i have this lines of code and i wonder how can i loop them in a for loop
outLoop = [2]
for r = 1 : length(outLoop)
r = outLoop(r);
y05_1 = mean(vertcat(y{:,r,m,1}),1);
y05_2 = mean(vertcat(y{:,r,m,2}),1);
y05_3 = mean(vertcat(y{:,r,m,3}),1);
y05_4 = mean(vertcat(y{:,r,m,4}),1);
y05_5 = mean(vertcat(y{:,r,m,5}),1);
filter = (x1>3);
x2 = x1(filter);
y05_1 = y05_1(filter);
y05_2 = y05_2(filter);
y05_3 = y05_3(filter);
y05_4 = y05_4(filter);
y05_5 = y05_5(filter);
%%% Best fit line for the observed points
p1 = polyfit(x2,y05_1,1);
y1 = polyval(p1,x2);
p2 = polyfit(x2,y05_2,1);
y2 = polyval(p2,x2);
p3 = polyfit(x2,y05_3,1);
y3 = polyval(p3,x2);
p4 = polyfit(x2,y05_4,1);
y4 = polyval(p4,x2);
p5 = polyfit(x2,y05_5,1);
y5 = polyval(p5,x2);
slope1 = p1(1);
slope2 = p2(1);
slope3 = p3(1);
slope4 = p4(1);
slope5 = p5(1);
slopes_5 = [slope1,slope2,slope3,slope4,slope5];
stdofslopes_05 = std(slopes_5);

채택된 답변

Rik 2022년 4월 11일
Replace numbered variables with arrays.
outLoop = 2;
filter = (x1>3);
x2 = x1(filter);
for r = 1 : numel(outLoop)
r = outLoop(r); % This is odd. You shouldn't overwrite the loop variable
for ind=1:5
y05{ind} = mean(vertcat(y{:,r,m,ind}),1);
y05{ind} = y05{ind}(filter);
%%% Best fit line for the observed points
p = polyfit(x2,y05{ind},1);
y_{ind} = polyval(p,x2);
slopes(ind) = p(1);
stdofslopes_05 = std(slopes);
  댓글 수: 1
lena kappa
lena kappa 2022년 4월 11일
편집: lena kappa 2022년 4월 12일
@Rik thank you so much!!!

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

추가 답변(0개)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by