How to increase the efficiency of this MATLAB program by using vectorization techniques

1 visualización (últimos 30 días)
I have a MATLAB code snippet as below. For now I have tried two versions of implementation to apply a function standard_deviation_distance to each element in an array. I wonder if there are any potential improvements on the code efficiency/performance in terms of the running time optimization (i.e., I hope the code can be run as fast as possible). Any suggestions will be greatly appreciated!
P.S. Please see the file nodetraffic.mat in the attached
load nodetraffic.mat;
% Method I
tic
count1 = 0;
for i = 1 : length(nodetraffic)
if (standard_deviation_distance(nodetraffic, nodetraffic(i)) > 6)
count1 = count1 + 1;
end
end
count1
toc
%% Method II
tic
A = arrayfun(@(x) standard_deviation_distance(nodetraffic, x), nodetraffic);
count2 = length(A(A > 6))
toc
function dist = standard_deviation_distance(v, x)
standard_deviation = std(v);
dist = (x - mean(v)) / standard_deviation;
end

Respuesta aceptada

Rik
Rik el 27 de Oct. de 2021
Arrayfun will only hide the loop, so it will never be faster than a plain for loop.
What you need to do is change your function so it allows array inputs. As far as I can tell, there is only a small change required.
fn=websave('data.mat','https://www.mathworks.com/matlabcentral/answers/uploaded_files/780763/nodetraffic.mat');
S=load(fn);
nodetraffic=S.nodetraffic;
method1(nodetraffic)
ans = 24
method2(nodetraffic)
ans = 24
%warm up the run online engine
timeit(@()method1(nodetraffic));timeit(@()method2(nodetraffic));
timeit(@()method1(nodetraffic)),timeit(@()method2(nodetraffic))
ans = 0.2317
ans = 5.2963e-05
function count=method1(nodetraffic)
count = 0;
for i = 1 : length(nodetraffic)
if (standard_deviation_distance(nodetraffic, nodetraffic(i)) > 6)
count = count + 1;
end
end
end
function count=method2(nodetraffic)
d=standard_deviation_distance(nodetraffic, nodetraffic);
count=sum(d>6);
end
function dist = standard_deviation_distance(v, x)
standard_deviation = std(v);
dist = (x - mean(v)) ./ standard_deviation;
% ^
% only change required here
end

Más respuestas (0)

Categorías

Más información sobre Functions en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by