だけので、この質問は未解決のままではない:私のR2016b + Win10 x64で
function q42372466(DO_SUM)
if ~nargin % nargin == 0
DO_SUM = true;
end
% Generate some data:
P = rand(2E7,2);
% Correctness:
R{1} = m1(P);
R{2} = m2(P);
R{3} = m3(P);
R{4} = m4(P);
R{5} = m5(P);
R{6} = m6(P);
for ind1 = 2:numel(R)
assert(abs(R{1}-R{ind1}) < 1E-10);
end
% Benchmark:
t(1) = timeit(@()m1(P));
t(2) = timeit(@()m2(P));
t(3) = timeit(@()m3(P));
t(4) = timeit(@()m4(P));
t(5) = timeit(@()m5(P));
t(6) = timeit(@()m6(P));
% Print timings:
disp(t);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Original method:
function out = m1(P)
if DO_SUM
out = sum(sqrt(P(:,1).^2 + P(:,2).^2))/max(size(P));
else
out = mean(sqrt(P(:,1).^2 + P(:,2).^2));
end
end
% pdist2 method:
function out = m2(P)
if DO_SUM
out = sum(pdist2([0,0],P))/max(size(P));
else
out = mean(pdist2([0,0],P));
end
end
% Shortened method #1:
function out = m3(P)
if DO_SUM
out = sum(sqrt(sum(P.*P,2)))/max(size(P));
else
out = mean(sqrt(sum(P.*P,2)));
end
end
% Shortened method #2:
function out = m4(P)
if DO_SUM
out = sum(sqrt(sum(P.^2,2)))/max(size(P));
else
out = mean(sqrt(sum(P.^2,2)));
end
end
% hypot
function out = m5(P)
if DO_SUM
out = sum(hypot(P(:,1),P(:,2)))/max(size(P));
else
out = mean(hypot(P(:,1),P(:,2)));
end
end
% (a+b)^2 formula , Divakar's idea
function out = m6(P)
% Since a^2 + b^2 = (a+b)^2 - 2ab,
if DO_SUM
out = sum(sqrt(sum(P,2).^2 - 2*prod(P,2)))/max(size(P));
else
out = mean(sqrt(sum(P,2).^2 - 2*prod(P,2)));
end
end
end
代表的な結果:
>> q42372466(0) % with mean()
0.1165 0.1971 0.2167 0.2161 0.1719 0.2375
>> q42372466(1) % with sum()
0.1156 0.1979 0.2233 0.2181 0.1610 0.2357
あなたの方法は、実際に上記のが最良であることを意味し、かなりのマージンで!
(正直なところ - 期待していませんでした)
あなたの現在の方法には何が問題なのですか(それは正しい値を提供していませんか?あなたは突然突然['integral2'](https://www.mathworks.com/help/matlab/ref/integral2.html)に切り替える必要がありますか?これは宿題ですか?入力を説明するのではなく、質問に追加するだけです。それほど大きなものではありません。 –
お返事ありがとうございます。理由;私はすぐに何百もの職場で働き、私の先生によれば、関数integral2ははるかに速く、より正確です(私はなぜそれを知っていません)。 –
StatisticsとMachine Learning Toolboxがあれば 'pdist2'があります。 'integral2'はオープンソースなので、そこには魔法はありません。私の知る限り、あなたの方法はほぼ理想的です。いずれにしても、最良のアプローチが何であるかを決定する前に、常にソリューションのベンチマークを行う必要があります。 –