Matrix - Vector value matching
5 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
the cyclist
on 1 Aug 2019
Edited: the cyclist
on 1 Aug 2019
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);
0 Comments
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!