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

조회 수: 15 (최근 30일)
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

채택된 답변

Adam Danz
Adam Danz 2019년 12월 17일
편집: Adam Danz 2019년 12월 18일
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:

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by