How to Vectorize this Code?

4 ビュー (過去 30 日間)
Krishan Bansal
Krishan Bansal 2022 年 9 月 21 日
コメント済み: Krishan Bansal 2022 年 9 月 21 日
I have this 147000 x 3 array, where each index represents a 3D vector. I want to use the vector at each index to find the angle between it and a predefined vector "b0" [ 0 1 0], this results in a 147000 x 1 array where each index has a single angle. I have been able to do this by using a normal for loop, however I was wondering if there was a way to vectorize this so it will be faster. I have been trying, but it either says that it can't do the dot product because arrays are of incompatible size, or it will only calculate the angle of the first index, then copy that 147000 times into the Nx1 array.
Thanks for any help.
  4 件のコメント
Matt J
Matt J 2022 年 9 月 21 日
@Krishan Bansal Please post your code and output as text, not images, to facilitate copy/pasting.
Krishan Bansal
Krishan Bansal 2022 年 9 月 21 日
@Matt J ok the code is just:
n3Array = squeeze(Orientation4D(:, 1, 1,1:3));
N = length(n3Array);
b0angles = zeros(N,1);
for i = 1:N
b0angles(i) = rad2deg(acos(dot(n3Array(i,:), b0)/(norm(n3Array(i,:)) * norm(b0))));
end

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

採用された回答

Matt J
Matt J 2022 年 9 月 21 日
編集済み: Matt J 2022 年 9 月 21 日
n3Array=normalize(n3Array,2,'n');
b0=b0/norm(b0);
b0angles=acosd(n3Array*b0);
  11 件のコメント
James Tursa
James Tursa 2022 年 9 月 21 日
This creates complex doubles?
n3Array = squeeze(Orientation4D(:, 1, 1,1:3));
b0 = [0 1 0];
n3Array = normalize(n3Array,2,'n');
b0 = b0/norm(b0);
b0angles = acosd(n3Array*b0(:));
Krishan Bansal
Krishan Bansal 2022 年 9 月 21 日
@James Tursa That worked perfectly, I forgot to use the normalized version of n3 I think. Thanks so much! This is super concise and efficient code.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by