Create a for loop and save the values in different columns
Show older comments
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)
KSSV
on 10 Dec 2018
0 votes
Read about knnsearch. YOu should use this function to get what you want.
5 Comments
Sofie Petersson
on 10 Dec 2018
KSSV
on 10 Dec 2018
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
Sofie Petersson
on 10 Dec 2018
Sofie Petersson
on 10 Dec 2018
Sofie Petersson
on 10 Dec 2018
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!