How to speed up a for loop ?

1 回表示 (過去 30 日間)
Sleh Eddine Brika
Sleh Eddine Brika 2016 年 10 月 6 日
編集済み: elias GR 2016 年 10 月 6 日
I have a matrix A n*3 of normal, I want to calculate the angles as shown in the code
angle=zeros(length(A),1);
for i = 1 : length(A)
n=A(i,:);
angle(i)=asin((n(3))/(sqrt(n(1).^2+n(2).^2+n(3).^2)));
end
It works but since I am dealing with really big matrices I need to speed this up. I tried this way, but it doesn't works.
angle=asin(A(:,3))/(sqrt(A(:,3).^2+A(:,2).^2+A(:,1).^2));

採用された回答

George
George 2016 年 10 月 6 日
Are you sure this is correct?
angle=asin(A(:,3))/(sqrt(A(:,3).^2+A(:,2).^2+A(:,1).^2));
That's doing matrix division. In your example, because of your loop, you are doing elementwise division. Fso
angle=asin(A(:,3)) ./ (sqrt(A(:,3).^2+A(:,2).^2+A(:,1).^2));
  1 件のコメント
Sleh Eddine Brika
Sleh Eddine Brika 2016 年 10 月 6 日
Thanks, I didn't thought about that

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

その他の回答 (3 件)

Massimo Zanetti
Massimo Zanetti 2016 年 10 月 6 日
Operate on rows, not columns:
angle=asin(A(3,:))/(sqrt(A(3,:).^2+A(2,:).^2+A(1,:).^2));
This will work.
  1 件のコメント
Guillaume
Guillaume 2016 年 10 月 6 日
編集済み: Guillaume 2016 年 10 月 6 日
No it won't. The / should be ./
There is also no issue operating on columns or rows (whatever that mean).

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


Guillaume
Guillaume 2016 年 10 月 6 日
編集済み: Guillaume 2016 年 10 月 6 日
It looks like A is a 2D matrix with a variable number of rows and 3 columns. If so, does not use length for getting the number of rows as it will return the number of columns if you have less than 3 rows. Use size(A, 1) to get the number of rows.
No loop is needed to get your result:
angle = asin(A(:, 3) ./ sqrt(sum(A.^2, 2)))
Your issue is that you want to do elementwise division so you need ./ instead of /.
I've also simplified your square root expression.

elias GR
elias GR 2016 年 10 月 6 日
編集済み: elias GR 2016 年 10 月 6 日
If A have 3 rows and n columns, try that:
angle=asin(A(3,:))./(sqrt(A(3,:).^2+A(2,:).^2+A(1,:).^2));
  2 件のコメント
Sleh Eddine Brika
Sleh Eddine Brika 2016 年 10 月 6 日
Sorry just a typo, A is n*3 matrix
elias GR
elias GR 2016 年 10 月 6 日
編集済み: elias GR 2016 年 10 月 6 日
Furthermore, I think that the equation that you use is not correct for 3D vectors.

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

カテゴリ

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