# Index in position 1 is invalid. Array indices must be positive integers or logical values.

40 views (last 30 days)
Zhou Ci on 5 Oct 2021
Commented: Star Strider on 6 Oct 2021
Hello,
I am trying to find the values of variable Z at the indices of lat_txt and lon_txt.
[m,n] = size(M) ; % m= 2030, n =1354
x0 = min(lon(:)) ; x1 = max(lon(:)) ;
y0 = min(lat(:)) ; y1 = max(lat(:)) ;
x = linspace(x0,x1,m) ;
y = linspace(y0,y1,n) ;
[X,Y] = meshgrid(x,y) ;
Z = interp2(X,Y,M',lon,lat)';
Z = Z'; %2030x1354
Out = Z(lat_txt, lon_txt);
Index in position 1 is invalid. Array indices must be positive integers or logical values.
lat_txt = 8119x1 double (containing lat values);
lon_txt = 8119x1 double(containing lon values);
Z contains integers 1,2,3,4. How can I find value of Z? As it gives me error here. However for each lat lon I just want one value of Z.

Star Strider on 5 Oct 2021
To reference ‘Z’ as a matrix, ‘lat’ and ‘lon’ must be integers greater than 0, or logical values.
The griddata function may be the best option here, speciffically —
Z = griddata(X(:),Y(:),reshape(M',numel(M),1),lon,lat)';
I cannot test this because I have none of the variables. However this is more llikely to produce the desired result than interp2, at least in the context of the posted code. Since I have no idea what the variables are and cannot test this, it may need to be tweaked.
.
Star Strider on 6 Oct 2021
It is not correct now for the same reason it was not correct this morning.
Use the griddata call (or something similar to it, since I cannot test it with the data that I do not have access to) that I posted in my previous Comment, instead of using ‘lat’ and ‘lon’ as indices into ‘Z’, that will never work, for the same reasons I described earlier.
.