How to compare each element of two arrays fullfilling a set condition more efficiently / quickly?
4 views (last 30 days)
Show older comments
I need to compare to each element of an array to each element within another array under the conidition that the elements are only allowed to differ within a specific tolerance range. Afterwards I want to extract the values from each array fullfilling the set condition. I have already figured it out for arrays with a small number of elements (see the code below). However, it appears to be way to slow for the comparison of large arrays, e.g. A and B being [>20000 x 1] since the iteration of the for loops explodes due to iteration count is equal to the array size to the power of two. Is there a more effiecent/ faster way to conduct the comparison and value extraction?
A = randi([0,5],10,1);
B = randi([0,5],10,1);
i=0;
err = 0.5; % error range for if statement
for k = 1:10
for m = 1:10
i=i+1;
if A(k)<(1+err)*B(m) && A(k)>(1-err)*B(m) % basically, B-value*0.5 < A < B-value*1.5
row(i,1)= k; % noting the row of A which fullfills the if condition
row(i,2)= m; % noting the row of B which fullfills the if condition
end
end
end
search_row = find(row(:,1)>1); % finding the non-zero rows
nnz_row = row(search_row,:); % extracting the non-zero rows
res(:,1) = A(nnz_row(:,1)); % extratcting the values from array A which fullfill the if condition
res(:,2) = B(nnz_row(:,2)); % extratcting the values from array B which fullfill the if condition
2 Comments
KSSV
on 14 Feb 2023
You need to initialize the variable row inside the for loop for impoving speed.
row = zeros([],2) ;
Include the above line before the for loop.
Accepted Answer
KSSV
on 14 Feb 2023
A = randi([0,5],10,1);
B = randi([0,5],10,1);
err = 0.5;
[a,b] = meshgrid(A,B) ;
idx = a<(1+err)*b & a>(1-err)*b ;
res = [a(idx) b(idx)] ;
More Answers (0)
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!