How can I extract a value from 2-d matrix based on the row and column indexes?

16 views (last 30 days)
Thanks anybody can tell me how can I extract a specific value from 2d matrix.
For example:
x = x(m,n) %----> lon values
y = y(m,n) %----> lat values
var=var(m,n)
I want to extract value from "var" at the lon = -69.19 and lat = 35.17

Accepted Answer

Adam Danz
Adam Danz on 17 Dec 2019
Edited: Adam Danz on 18 Dec 2019
Define the targets variable and then run this on your data. The variable varAtTarget is your output.
This finds the nearest latitude and longitude coordinate to your target and returns the corresponding var value. However, I strongly urge you to rename the var variable since var() is a common Matlab function.
I added a couple extra steps to show how to print the outputs to the command window.
% Find the index to the closest lat and lon that equals the target values
targets = [-69.19, 35.17]; % [lon,lat] since you x seems to be Longitude and your y seems to latitudes
% Compute distance between targets and all (x,y) coordinates
d = pdist2(targets,[x(:),y(:)]);
% Find the nearest coordinate
[minDist, minIdx] = min(d);
% Output the corresponding var
varAtTarget = var(minIdx);
% Get row,col number
[rowNum,colNum] = ind2sub(size(x),minIdx);
% Output a summary text so you can determine whether the outputs make sense.
fprintf(['The closest coordinates to target [%.2f, %.2f] is coordinate [%.2f, %.2f]\nat index %d '...
'(row %d, col %d) which is at a distance of %.2f from the target.\nVar at that coordinate is %.2f.\n'], targets, ...
x(minIdx), y(minIdx), minIdx, rowNum, colNum, minDist, varAtTarget)
Result:

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices 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!