Cross Product of Each Row in Two Large Arrays

37 views (last 30 days)
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).

Accepted Answer

dpb
dpb on 14 Jul 2021
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.

More Answers (0)

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!