Search code examples
matlabloopsfor-looplinear-regressionnested-loops

How to Nest a Loop so the Entire Thing Repeats 100X


I have a loop that I am trying to create another loop around, but I'm not sure what the syntax should be. Here is my code:

for (?)
    for i=1:6
        r(i)=normrnd(0,0.1*sy);
        y_new=A+B*x+r;
    end
    % estimate new A and B
    [mm,nn]=size(x); DoF=mm-2;
    x_mean=mean(x);
    y_mean=mean(y_new);
    xp=(x-x_mean);
    yp=(y_new-y_mean);
    num=sum(xp.*yp);
    dem=sum(xp.*xp);
    B_new=num/dem;
    A_new=y_mean-B_new*x_mean;
end

I'm not sure what to put in the for loop to make it repeat 100X. I assume I need "for i=1:100" but then I'm not sure where in the loop to put set my x(i) to get the intended result. I'm not even sure if I nested the first loop in there correctly. I am trying to create a set of 6 new y values using normrnd and then run a linear regression to generate a new A and B (slope and intercept), and then I want to repeat that entire process 100X.


Solution

  • Unless you have a specific reason not to vectorize your normrnd() calls, you only need one level of fors:

    %sy,A,B,x initialized elsewhere
    for i=1:100
        r=normrnd(0,0.1*sy,[6 1]);
        y_new=A+B*x+r;
        clear r;
    
        % estimate new A and B
        [mm,nn]=size(x);
        DoF=mm-2;
        x_mean=mean(x);
        y_mean=mean(y_new);
        xp=(x-x_mean);
        yp=(y_new-y_mean);
        num=sum(xp.*yp);
        dem=sum(xp.*xp);
        B_new=num/dem;
        A_new=y_mean-B_new*x_mean;
        %set B=B_new and A=A_new for the next iteration maybe?
    end
    clear i;