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

1 view (last 30 days)
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.

Accepted Answer

Chunru
Chunru on 8 Jul 2021
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

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!