フィルターのクリア

Index of Array's column whose value is closest to Vector value for a given row

1 回表示 (過去 30 日間)
Paul MAUGER
Paul MAUGER 2021 年 7 月 8 日
コメント済み: Paul MAUGER 2021 年 7 月 8 日
Ia ora na,
I spent some time here but didn't get the hint I was looking for (yet). So, let's explain my problem. I have 2 sets : 1 vector and 1 array, same number of rows, as for example :
N = 20;
A = 1 + 4*rand(N,1); % Generate column vector of N value from 1 to 5
B = [1:0.1:5]; % Generate line vector of 41 value ranging from 1 to 5 by 0.1 step
B = repmat(B,N,1); % Replicate such vector N times
I need to get a vector idx of size [N 1] that for each rows of A(i) and B(i,:) gives me the column number of B which contains the closest value of A(i), id est : if A(1) = 3 then idx(1) should return 21 because B(1,21) = 3 is the closest value to A(1).
With or without loops, I've no idea how to get there. I already tried with find function with a loop, also the " min(abs(A-B) " thing I've seen here and there, but couldn't figure out how to get the result I need.
Thanks for your help.

採用された回答

Chunru
Chunru 2021 年 7 月 8 日
N = 20;
A = 1 + 4*rand(N,1); % Generate column vector of N value from 1 to 5
B = [1:0.1:5]; % Generate line vector of 41 value ranging from 1 to 5 by 0.1 step
B = repmat(B,N,1); % Replicate such vector N times
idx = zeros(N,1);
for i=1:N
[~, idx(i)] = min(abs(A(i) - B(i, :)));
end
idx'
ans = 1×20
22 23 17 21 17 2 20 16 38 33 17 39 23 15 16 2 40 19 10 22

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by