Create a for loop and save the values in different columns

I have problems creating a for loop in my matlab script. Have tried for a while but don't really get the solution I want.
I have three different locations and the coordinates for these can be found in coordlat and coordlon. I want to run my program for all the locations after eachother and then finally save the answers in a matrix, a new column for each location.
Here follows the code I have right now.
format long
ncfil00 = 'met_forecast_1_0km_nordic_20180601T00Z.nc';
ncfil01 = 'met_forecast_1_0km_nordic_20180601T01Z.nc';
lat=ncread(ncfil00,'latitude');
lon=ncread(ncfil00,'longitude');
temp00 = ncread(ncfil00,'air_temperature_2m');
temp01 = ncread(ncfil01,'air_temperature_2m');
coordlat=[63.2831 65.0942 68.4217];
coordlon=[12.1246 14.5085 18.1719];
for i=1:length(coordlat)
for j=1:length(coordlon)
distance = ( coordlat(i) - lat(:) ).^2 + ( coordlon(j) - lon(:) ).^2;
[~, index] = min(distance);
Temperaturejune2018(1,i) = temp00(index)-273.15;
Temperaturejune2018(2,i) = temp01(index)-273.15;
end
end

回答(1 个)

Read about knnsearch. YOu should use this function to get what you want.

5 个评论

Sorry, I'm asking for help about the for loop. The other things are fine.
count = 0 ;
for i=1:length(coordlat)
for j=1:length(coordlon)
distance = ( coordlat(i) - lat(:) ).^2 + ( coordlon(j) - lon(:) ).^2;
[~, index] = min(distance);
count = count+1 ;
Temperaturejune2018(1,count) = temp00(index)-273.15;
Temperaturejune2018(2,count) = temp01(index)-273.15;
end
end
Thanks, almost there. But now I get a matrix 2x9, I only want 2x3...
Do you know what I can change to get that?
Tried to do like this now, but I get this error: Assignment has more non-singleton rhs dimensions than non-singleton subscripts
count=0;
for i=1:length(coordlat), j=1:length(coordlon);
distance = ( coordlat(i) - lat(:) ).^2 + ( coordlon(j) - lon(:) ).^2;
[~, index] = min(distance);
count=count+1;
Temperaturejune2018(1,count) = temp00(index)-273.15;
Temperaturejune2018(2,count) = temp01(index)-273.15;
end

请先登录,再进行评论。

类别

帮助中心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!

Translated by