Nested Loop gives only last calculation as output

1 view (last 30 days)
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 Comment
Stephen23
Stephen23 on 15 Aug 2017
Edited: Stephen23 on 15 Aug 2017
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?

Sign in to comment.

Answers (1)

KL
KL on 15 Aug 2017
Edited: KL on 15 Aug 2017
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
In addition to that name it more sensibly than just i and j, read here to know why.
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 Comments
Vraj Pandya
Vraj Pandya on 15 Aug 2017
I am Beginner and i this is the question Que : Determine the monthly precipitation and temperature for year 1960, 1968, 1985, 1992, and 2008 for each station. P.S. they gave us the file where data for precipitation and temperature is given
Stephen23
Stephen23 on 15 Aug 2017
Edited: Stephen23 on 15 Aug 2017
@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.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements 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!