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

5 ビュー (過去 30 日間)
Akash Bhuwal
Akash Bhuwal 2021 年 5 月 6 日
編集済み: Jan 2021 年 5 月 6 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by