Fastest way to find the values and indices of the entries of a vector X that are closest to each entry of a matrix A.
3 次查看(过去 30 天)
显示 更早的评论
Basically wondering if there is a faster way to do something like this:
X = [0:.05:1]; % the vector
A = rand(100); % the matrix
result_val = zeros(100);
result_idx = zeros(100);
for i = 1:100
for j = 1:100
[result_val(i,j), result_idx(i,j)] = min( abs(A(i,j) - X) );
end
end
0 个评论
采纳的回答
Githin George
2024-12-6
You can vectorize the operation as shown below:
X = 0:0.05:1; % the vector
A = rand(5000); % the matrix
%% Vectorized Approach
tic
% Reshape X to create 1x1xsize(X) array
X = reshape(X, 1, 1, []);
% Calculate the absolute differences NxNxsize(X)
differences = abs(A - X);
% Find the minimum differences and their indices along dim=3
[result_val, result_idx] = min(differences, [], 3);
toc
%% Non Vectorized Approach
tic
result_val1 = zeros(5000);
result_idx1 = zeros(5000);
for i = 1:5000
for j = 1:5000
[result_val1(i,j), result_idx1(i,j)] = min( abs(A(i,j) - X) );
end
end
toc
%%
disp("isequal(result_val,result_val1) output: "+ isequal(result_val1,result_val))
2 个评论
Image Analyst
2024-12-6
If you want to wait for additional answers using different approaches, you can.
If this Answer solves your original question, then could you please click the "Accept this answer" link to award the answerer with "reputation points" for their efforts in helping you? They'd appreciate it. Thanks in advance. 🙂 Note: you can only accept one answer (so pick the best one) but you can click the "Vote" icon for as many Answers as you want. Voting for an answer will also award reputation points.
For full details on how to earn reputation points see: https://www.mathworks.com/matlabcentral/answers/help?s_tid=al_priv#reputation
更多回答(1 个)
Matt J
2024-12-7
编辑:Matt J
2024-12-7
result_idx = reshape( interp1(X,1:numel(X),A(:),'nearest','extrap') ,size(A));
result_val=abs(X(result_idx)-A);
2 个评论
Matt J
2024-12-7
编辑:Matt J
2024-12-7
Speed comparison:
X = linspace(0,1,500); % the vector
A = rand(1000); % the matrix
%%Using min
tic
% Calculate the absolute differences NxNxsize(X)
differences = abs(A - reshape(X, 1, 1, []));
% Find the minimum differences and their indices along dim=3
[result_val, result_idx] = min(differences, [], 3);
toc
%%Using interp1
tic;
result_idx = reshape( interp1(X,1:numel(X),A(:),'nearest','extrap') ,size(A));
result_val=abs(X(result_idx)-A);
toc
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!