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

1 回表示 (過去 30 日間)
hmhuang
hmhuang 2021 年 10 月 27 日
回答済み: Rik 2021 年 10 月 27 日
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

採用された回答

Rik
Rik 2021 年 10 月 27 日
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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by