How to compare two numbers in two different vectors and save without using for loop?

5 visualizzazioni (ultimi 30 giorni)
I have the below code
nodeMat = zeros(size(mainNodes,1),3); count = 0;
for i=1:size(allNodes,1)
for j=1:size(mainNodes,1)
if isalmost(mainNodes(j,2),allNodes(i,1),1e-4) && ...
isalmost(mainNodes(j,3),allNodes(i,2),1e-4)
count = count + 1;
nodeMat(count,:) = [i mainNodes(j,2) mainNodes(j,3)];
end
end
end
wher allNodes, mainNodes are given vectors containing float numbers. i have to run this code many times and to make it faster i dont want ot use cluster for loop.
Can someone please help?
Thanks in advance

Risposta accettata

Jan
Jan il 6 Mag 2021
Modificato: Jan il 6 Mag 2021
The implementation of isalmost is not efficient. It is faster to check the values directly:
nodeMat = zeros(size(mainNodes,1),3);
count = 0;
for i = 1:size(allNodes,1)
for j = 1:size(mainNodes,1)
if abs(mainNodes(j,2) - allNodes(i,1)) <= 1e-4 && ...
abs(mainNodes(j,3) - allNodes(i,2)) <= 1e-4
count = count + 1;
nodeMat(count,:) = [i mainNodes(j,2) mainNodes(j,3)];
end
end
end
nodeMat = nodeMat(1:count, :);
For this input:
mainNodes = randi([1, 10], 1000, 3);
allNodes = randi([1, 10], 1000, 2);
my Matlab R2018b runs the code in 0.039 seconds instead of 2.11 seconds with isalmost. 53 times faster.
Now lets check, if a vectorization is useful...
nodeMat = zeros(size(mainNodes,1),3);
count = 0;
for i = 1:size(allNodes,1)
match = abs(mainNodes(:,2) - allNodes(i,1)) <= 1e-4 & ...
abs(mainNodes(:,3) - allNodes(i,2)) <= 1e-4;
n = sum(match);
if n ~= 0
nodeMat(count + 1:count + n, 1) = i;
nodeMat(count + 1:count + n, 2) = mainNodes(match, 2);
nodeMat(count + 1:count + n, 3) = mainNodes(match, 3);
count = count + n;
end
end
nodeMat = nodeMat(1:count, :);
% 0.015610 seconds
My trials for a fully vectorized methods are not faster.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by