Matrix - Vector value matching

2 ビュー (過去 30 日間)
Brandon Bush
Brandon Bush 2019 年 8 月 1 日
編集済み: the cyclist 2019 年 8 月 1 日
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 Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by