Nested Loop gives only last calculation as output
2 次查看(过去 30 天)
显示 更早的评论
clear all
station1=dlmread('D:\MTECH\Hydrology\MATLAB\precip_data\data_8.375_77.375');
year=[1960 1968 1985 1992 2008]';
m=[1:1:12]';
out1=[];
out=[];
for j=1:size(year,1)
yr=year(j,1);
aa=find(station1(:,1)==yr);
mm=station1(aa,:);
for i=1:size(m,1)
mnth=m(i,1);
bb=find(mm(:,2)==mnth);
out(i,1)=yr;
out(i,2)=mnth;
out(i,3)=sum(station1(bb,4));
i=i+1;
end
j=j+1;
dlmwrite('Q1P_station1.txt',out);
end
1 个评论
Stephen23
2017-8-15
编辑:Stephen23
2017-8-15
Note that it there is not point in incrementing i and j at the end of the loop: the for already does this for you so it is just misleading and serves no purpose.
It seems like you are trying to collect year and month data together: is this correct? Why do you keep overwriting the same file?
Given that you have dlmwrite('Q1P_station1.txt',out) at the end of the outer loop, why do you need to store all data anyway?
回答(1 个)
KL
2017-8-15
编辑:KL
2017-8-15
Yes, It is because you're overwriting the same file in all your iterations.
There's no sample data to run your code but anyway, I noticed few things on your code that I wanted to address.
1. Variable names and assignment.
You don't actually need to use square brackets for scalars and when you want to transpose a row vector to a column one, you could use round brackets -> ( and ) instead of [ and ] .
2. Loop syntax
Unlike C or C++, in Matlab you don't need to increment your iterating variable. So you don't need i = i+1 or j = j+1
Also if you're interested in improving, read more on vectorization. Apart from this, as a general coding practice you could make your code a lot simpler just by reading the documentation .
3 个评论
Stephen23
2017-8-15
编辑:Stephen23
2017-8-15
@Vraj Pandya: do not expand out inside the loop. Preallocate out to the correct size before the loop: you know the size because you know how many months, years, and data values you need (I probably use an ND array to make this simpler).
Then simply use indexing to allocate the values, and you will be finished.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!