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!