MATLAB Answers

Cross Product of Each Row in Two Large Arrays

조회 수: 3(최근 30일)
Jonathan Krenzel
Jonathan Krenzel 2021년 7월 14일
댓글: Jonathan Krenzel 2021년 7월 14일
I have two large arrays whose dimensions are (n,3) where n is the number of components in the system. In order to calculate the result of each component, I need to take the cross product of those two arrays for each n within the array. Is there a more computationally efficient way to do so besides using the following code?
n = number_of_components;
for i = 1:n
RESULT(i,:) = cross([x1(i) x2(i) x3(i)], [y1(i) y2(i) y3(i)]);
end
The above code works fine; however, the run time starts becoming a problem for a system containing thousands of components (n >> 1000).

채택된 답변

dpb
dpb 2021년 7월 14일
Description
C = cross(A,B) returns the cross product of A and B.
...
If A and B are matrices or multidimensional arrays, ... the function calculates
the cross product of corresponding vectors along the first array dimension whose size equals 3.
So, all you need to write is
res=cross(x,y);
You may be able to help just a tiny fraction by giving it the dimension over which to operate as the third optional parameter which will save the overhead of determining that direction internally.
res=cross(x,y,2);
Of course, the explicit loop above will begin to bog down as N becomes large if you haven't preallocated the output array first--but even with that, undoubtedly the internal function will beat it handily.

추가 답변(0개)

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by