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!