Nested Loop gives only last calculation as output

조회 수: 2 (최근 30일)
Vraj Pandya
Vraj Pandya 2017년 8월 15일
편집: Stephen23 2017년 8월 15일
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
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
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
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
Vraj Pandya
Vraj Pandya 2017년 8월 15일
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 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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by