How to remove for loops from a code

조회 수: 1 (최근 30일)
Matteo
Matteo 2014년 1월 22일
편집: Andrei Bobrov 2014년 1월 22일
I've to remove for loops from a code to speed it up.
the code is:
function [S p] = similarityMatrix(data,candidates)
[row,col] = size(data);
S = zeros(row,col,row*col);
if nargin == 1
candidates = 1:numel(data);
end
for z = 1 : numel(candidates)
c = candidates(z);
for i = 1 : row
for j = 1 : col
if c == sub2ind(size(data),i,j);
S(i,j,z) = NaN;
else
S(i,j,z) = -dist(data(c),data(i,j));
end
end
end
end
%aggiungo le preferenze
p = nanmedian(S(:));
S(isnan(S)) = p;
is there a way to improve it?

채택된 답변

Andrei Bobrov
Andrei Bobrov 2014년 1월 22일
편집: Andrei Bobrov 2014년 1월 22일
n = numel(data);
S = -abs(bsxfun(@minus,data,reshape(data(candidates),1,1,[])));
S(candidates + (0:numel(candidates)-1)*n) = nan;
p = nanmedian(S(:));
S(isnan(S)) = p;

추가 답변 (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