Matrix - Vector value matching

5 次查看(过去 30 天)
Matrix = magic(20);
Leroy = randi(20,20,1);
for i = 1:length(Leroy)
[Jenkins, J] = min(min(Leroy(i) - Matrix);
end
In my current project, I need to find values inside of an matrix that match with individual vector values. This is an example of the process; the main program has me using lat and lon values. But I create a 20x20 matrix and then a 20x1 array of randomly placed values.
When i do the for loop, each iteration of the Leroy vector is subtracted from every value in matrix. The first min function should return the smallest value from each column and its correspoding index. The second min function should return the smallest overall value from the first min function. and which index had the smallest value.
My concern is that im not sure which integer inside the matrix returned the smallest value. Is there a way I can use the indexes or something to figure that out?

采纳的回答

the cyclist
the cyclist 2019-8-1
编辑:the cyclist 2019-8-1
In each iteration of the for loop, you are looking for the closest value (regardless of whether it is larger or smaller)? One way to do that would
Jenkins = zeros(20,1);
J = zeros(20,1);
for i = 1:length(Leroy)
[Jenkins(i), J(i)] = min(abs(Leroy(i) - Matrix(:)));
end
Then Jenkins will be the minimum difference (in absolute terms), and J will be the linear index to the Matrix location. You can get the subscripted indices (i.e. row & column index) using
[m,n] = ind2sub([20,20],J);
You can read more about linear indexing in the documentation here.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by