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.
0 个评论
采纳的回答
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'
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!