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

5 次查看(过去 30 天)
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

采纳的回答

Jan
Jan 2021-5-6
编辑:Jan 2021-5-6
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by