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
2 个评论
Jan
2021-5-6
Should we assume that the function isalmost is coming from here: https://www.mathworks.com/matlabcentral/fileexchange/15816-isalmost ?
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!