2 乗演算のような単純なことを行うことはなく、実行しようとしていることが MATLAB でまだベクトル化されていないことを前提としています。
関数を一度呼び出して、関数内でループを実行することをお勧めします。要素の数が増えると、操作時間が大幅に増加することに気付くでしょう。
関数を次のようにします。
function result = getSquare(x)
result = x*x; % I did not use .* on purpose
end
function result = getSquareVec(x)
result = zeros(1,numel(x));
for idx = 1:numel(x)
result(:,idx) = x(idx)*x(idx);
end
end
そして、スクリプトからそれらを呼び出しましょう:
y = 1:10000;
tic;
for idx = 1:numel(y)
res = getSquare(y(idx));
end
toc
tic;
res = getSquareVec(y);
toc
コードを数回実行したところ、関数を 1 回呼び出すだけで少なくとも 2 倍高速であることがわかりました。
Elapsed time is 0.020524 seconds.
Elapsed time is 0.008560 seconds.
Elapsed time is 0.019019 seconds.
Elapsed time is 0.007661 seconds.
Elapsed time is 0.022532 seconds.
Elapsed time is 0.006731 seconds.
Elapsed time is 0.023051 seconds.
Elapsed time is 0.005951 seconds.