Nesting loop reiterating wrong code
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hello,
I would like to write a loop that runs 5000 times (rows) an equation that calculates 1 row of 8 columns of data. My code so far is:
for f=1:4999;
%Create an inner loop
for g=1:8
%Compute randomized slope
h=glmfit(arr(e,1),arr(e,g+1),'normal');
%Put randomized slope in slp
slp(g)=h(2);
end
%Computer differences in randomized treatment slopes
diff(f)=mean(slp(1:3))-mean(slp(4:8));
end
Instead of looping the calculation of the slope and the creation of the row of 8 slopes, it ends up looping just the calculation of the differences in randomized treatment slopes.
I'm rather new to MatLab (and self taught) so any advice would be greatly appreciated. Thank you !
Edit: Here is my code as a whole
%Read Original Data
arr=csvread('testdata.csv',1,0);
%Fit a linear model to each treatment, and put slopes in slpobs
a=zeros(1,8);
for b=1:8
c=glmfit(arr(:,1),arr(:,b+1),'normal');
d(b)=(c(2));
end
slpobs=transpose(d);
%Compute the observed differences between treatment means
diffobs=mean(d(1:3))-mean(d(4:8));
%Create randomized times
e=fix(random('uniform',1,176,176,1));
%Create array for randomized slopes
diff=zeros(1,4999);
%Create an outer loop
for f=1:4999
%Create an inner loop
for g=1:8
%Compute randomized slope
h=glmfit(arr(e,1),arr(e,g+1),'normal');
%Put randomized slope in slp
slp(g)=h(2);
end
%Computer differences in randomized treatment slopes
diff(f)=mean(slp(1:3))-mean(slp(4:8));
end
%Take the absolute value of randomized differences
absdiff=abs(diff);
%Find instances where the random difference exceeds the observed difference
index=sum(absdiff>=diffobs);
0 comentarios
Respuestas (2)
Brittany
el 28 de Nov. de 2011
Delete the semicolon from the end of your first for statement. That is probably why it is not doing the inner loop.
0 comentarios
Matt Tearle
el 28 de Nov. de 2011
Nothing inside your outer loop (except the indexed assignment at the end) references the loop variable f, so you're doing exactly the same calculation each time. Perhaps the line
h=glmfit(arr(e,1),arr(e,g+1),'normal');
should be
h=glmfit(arr(f+e,1),arr(f+e,g+1),'normal');
instead? Or something like that?
Also, if you're not already, preallocate your arrays!
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!