Conversion function taking a very long time to run in loop, anyway to improve?

1 回表示 (過去 30 日間)
JM
JM 2019 年 3 月 18 日
コメント済み: JM 2019 年 3 月 18 日
I created a function that does a simple conversion to my data with two coordinates being the input (below)
%%
function [ GazeDirDegrees ] = ConvertGazeDir( GazeDir1,GazeDir2 )
GazeDirDegrees = 180*asin(GazeDir1/sqrt(GazeDir1.^2+GazeDir2.^2))/pi
end
I am running this in a loop over 120 cells, with each cell containing 1000-1700 data points. As you can imagine this means that the function has to be called over 120,000 times. Not only that, but I have to run this loop 4 times for 4 different variables. (below is an example for just one variable))
%%
for i = 1:length(LeftGazeDirX)
for b = 1:length(FilteredLeftGazeDirX{1,i})
ConvLeftGazeDirX{b,i} = ConvertGazeDir(FilteredLeftGazeDirX{1,i}(b,1),FilteredLeftGazeDirZ{1,i}(b,1))
end
end
Not sure if there is anything I can do to make this run more efficiently, as it currently takes about 20 seconds for a single cells worth of data.

採用された回答

Walter Roberson
Walter Roberson 2019 年 3 月 18 日
編集済み: Walter Roberson 2019 年 3 月 18 日
Vectorize your formula by replacing the / with ./ and then you can pass in entire cells (provided the two cells are the same size)
Also you can improve performance slightly by making it 180/pi * .... instead of 180*.../pi so that the division by pi only has to be done once
Also consider using asind without the 180/pi
  1 件のコメント
JM
JM 2019 年 3 月 18 日
The vectorized solution worked great, thank you!

サインインしてコメントする。

その他の回答 (1 件)

Steven Lord
Steven Lord 2019 年 3 月 18 日
Call asind on arrays of data instead of on scalars. Use the hypot function if your data is real.
n = 100;
X = rand(n);
Y = rand(n);
tic
Z = asind(X./hypot(X, Y));
toc
tic
Z2 = asind(X./sqrt(X.^2+Y.^2));
toc
differenceBetweenApproaches = norm(Z-Z2)
The difference between the two approaches should be small.

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by