How to reduce computation time for this loop. My more than 90% of time is consume by this subsection
Show older comments
for h=1:r
dist(h, :) = sum(bsxfun(@minus, data(h,:), mtrx).^2, 2)';
end
I have tried parfor loop also, but this does not solve my problem. Instead of decreasing computation time. It increases computation time. Please help me to solve this problem.
Answers (2)
Sean de Wolski
on 19 Sep 2014
Is dist preallocated?
How much does it speed up if you run it backwards to dynamically preallocate?
for h = r:-1:1
dist(h, :) = sum(bsxfun(@minus, data(h,:), mtrx).^2, 2)';
end
3 Comments
kusum bharti
on 19 Sep 2014
kusum bharti
on 19 Sep 2014
José-Luis
on 19 Sep 2014
How big are r, data, and mtrx?
This works column-wise instead of row-wise and gives Euclidean distance instead of square distance, but is otherwise the same as what you've asked for,
function Graph=interdists(A,B)
%Finds the graph of distances between point coordinates
%
% (1) Graph=interdists(A,B)
%
% in:
%
% A: matrix whose columns are coordinates of points, for example
% [[x1;y1;z1], [x2;y2;z2] ,..., [xM;yM;zM]]
% but the columns may be points in a space of any dimension, not just 3D.
%
% B: A second matrix whose columns are coordinates of points in the same
% Euclidean space. Default B=A.
%
%
% out:
%
% Graph: The MxN matrix of separation distances in l2 norm between the coordinates.
% Namely, Graph(i,j) will be the distance between A(:,i) and B(:,j).
%
%
% (2) interdists(A,'noself') is the same as interdists(A), except the output
% diagonals will be NaN instead of zero. Hence, for example, operations
% like min(interdists(A,'noself')) will ignore self-distances.
%
% See also getgraph
noself=false;
if nargin<2
B=A;
elseif ischar(B)&&strcmpi(B,'noself')
noself=true;
B=A;
end
[N,M]=size(A);
B=reshape(B,N,1,[]);
Graph=sqrt(sum(bsxfun(@minus, A, B).^2,1));
Graph=reshape(Graph,M,[]);
if noself
n=length(Graph);
Graph(linspace(1,n^2,n))=nan;
end
Categories
Find more on Quaternion Math in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!