Nested Loop gives only last calculation as output
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Stephen23
el 15 de Ag. de 2017
Editada: Stephen23
el 15 de Ag. de 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?
Respuestas (1)
KL
el 15 de Ag. de 2017
Editada: KL
el 15 de Ag. de 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
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 comentarios
Stephen23
el 15 de Ag. de 2017
Editada: Stephen23
el 15 de Ag. de 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.
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!