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

15 vues (au cours des 30 derniers jours)
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

Réponse acceptée

Adam Danz
Adam Danz le 17 Déc 2019
Modifié(e) : Adam Danz le 18 Déc 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:
  2 commentaires
Farshid Daryabor
Farshid Daryabor le 18 Déc 2019
Dear Adam,
I really appreciate your comprehensive answer.
Thanks
Adam Danz
Adam Danz le 18 Déc 2019
I'm glad it was helpful!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by