# Problem with for loop and polyfit

2 views (last 30 days)
lena kappa on 11 Apr 2022
Edited: lena kappa on 12 Apr 2022
Hello everyone, i have this lines of code and i wonder how can i loop them in a for loop
outLoop = 
for r = 1 : length(outLoop)
r = outLoop(r);
m=5;
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);
end

Rik on 11 Apr 2022
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
m=5;
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);
end
stdofslopes_05 = std(slopes);
end
lena kappa on 11 Apr 2022
Edited: lena kappa on 12 Apr 2022
@Rik thank you so much!!!