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.
조회 수: 4 (최근 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!