필터 지우기
필터 지우기

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

조회 수: 1 (최근 30일)
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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by