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

Answers (1)

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

5 Comments

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

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 10 Dec 2018

Commented:

on 10 Dec 2018

Community Treasure Hunt

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

Start Hunting!