2 variable for-loop
3 views (last 30 days)
Show older comments
hello
I have the following code which I want to write it as a two variable for loop, Apparently I am making mistake that it gives the same values for all elements of results matrix
TKE_dave is a 19000*13 matrix
and
tp =[4833 6499 8165 9831 11497 13163 14829 16495 18161]
TKE_ave1=TKE_dave(:,1);
TKE_avep1=zeros(8,1);
for m=1:8
TKE_avep1(m,1)=nanmean(TKE_ave1(tp(m):tp(m+1)));
end
TKE_ave2=TKE_dave(:,2);
TKE_avep2=zeros(8,1);
for m=1:8
TKE_avep2(m,1)=nanmean(TKE_ave2(tp(m):tp(m+1)));
end
TKE_ave3=TKE_dave(:,3);
TKE_avep3=zeros(8,1);
for m=1:8
TKE_avep3(m,1)=nanmean(TKE_ave3(tp(m):tp(m+1)));
end
TKE_ave4=TKE_dave(:,4);
TKE_avep4=zeros(8,1);
for m=1:8
TKE_avep4(m,1)=nanmean(TKE_ave4(tp(m):tp(m+1)));
end
TKE_ave5=TKE_dave(:,5);
TKE_avep5=zeros(8,1);
for m=1:8
TKE_avep5(m,1)=nanmean(TKE_ave5(tp(m):tp(m+1)));
end
TKE_ave6=TKE_dave(:,6);
TKE_avep6=zeros(8,1);
for m=1:8
TKE_avep6(m,1)=nanmean(TKE_ave6(tp(m):tp(m+1)));
end
TKE_ave7=TKE_dave(:,7);
TKE_avep7=zeros(8,1);
for m=1:8
TKE_avep7(m,1)=nanmean(TKE_ave7(tp(m):tp(m+1)));
end
TKE_ave8=TKE_dave(:,8);
TKE_avep8=zeros(8,1);
for m=1:8
TKE_avep8(m,1)=nanmean(TKE_ave8(tp(m):tp(m+1)));
end
TKE_ave9=TKE_dave(:,9);
TKE_avep9=zeros(8,1);
for m=1:8
TKE_avep9(m,1)=nanmean(TKE_ave9(tp(m):tp(m+1)));
end
TKE_ave10=TKE_dave(:,10);
TKE_avep10=zeros(8,1);
for m=1:8
TKE_avep10(m,1)=nanmean(TKE_ave10(tp(m):tp(m+1)));
end
TKE_ave11=TKE_dave(:,11);
TKE_avep11=zeros(8,1);
for m=1:8
TKE_avep11(m,1)=nanmean(TKE_ave11(tp(m):tp(m+1)));
end
TKE_ave12=TKE_dave(:,12);
TKE_avep12=zeros(8,1);
for m=1:8
TKE_avep12(m,1)=nanmean(TKE_ave12(tp(m):tp(m+1)));
end
TKE_ave13=TKE_dave(:,13);
TKE_avep13=zeros(8,1);
for m=1:8
TKE_avep13(m,1)=nanmean(TKE_ave13(tp(m):tp(m+1)));
end
I tried to make it shorter and write it as the following two variable for-loop and for that I learend that I have to define a temporary matrix so I defined test matrix which is the same as TKE_dave actually
TKE_avep=zeros(8,13);
test=zeros(19000,13);
for m=1:8;
for ss=1:13;
test(:,ss)=TKE_dave(:,ss);
TKE_avep(m,ss)=nanmean(test(tp(m):tp(m+1)));
end
end
but it gives the same values for all the elemants of the result matrix.
can someone help me where is my mistake?
0 Comments
Accepted Answer
Bob Thompson
on 4 Nov 2019
The issue is with your definition of test. Nested for loops are totally fine.
test(:,ss)=TKE_dave(:,ss);
On your last loop test and TKE_dave will be the same matrix, whereas in your individual loops it is only each column. Replace test(:,ss) with just test.
More Answers (0)
See Also
Categories
Find more on Characters and Strings 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!