The MATLAB function `cross`

implements the vector product for two kinds of input data: a pair of vectors and a pair of N-D arrays. Surprisingly, it works slower for successive computations of cross products for 3-D vector pairs than the following naive implementation.

function C = cross3d(A, B) C = [A(2)*B(3) - A(3)*B(2), ... A(3)*B(1) - A(1)*B(3), ... A(1)*B(2) - A(2)*B(1)]; end

Further, we estimate the median running time of `cross`

and `cross3d`

in a reproducible way using MATLAB scripts.

We use median instead of mean to assess the time because median is robust to outliers which tend to occur due to MATLAB internal optimization routines. Also we consider two types of vector containers: a matrix and a cell array. The following scripts were launched on MATLAB R2015b: `testCrossMatrix.m`

for a matrix and `testCrossCell.m`

for a cell array.

N = 10^5; vectorA = rand(N, 3); vectorB = rand(N, 3); timesCross = zeros(N, 1); timesCross3d = zeros(N, 1); for i = 1:N tic(); cross3d(vectorA(i,:), vectorB(i,:)); timesCross3d(i) = toc(); end for i = 1:N tic(); cross(vectorA(i,:), vectorB(i,:)); timesCross(i) = toc(); end disp('Median cross time (vectors from a matrix): '); median(timesCross) disp('Median cross3d time (vectors from a matrix): '); median(timesCross3d)

N = 10^5; vectorA = cell(N, 1); vectorB = cell(N, 1); for i = 1:N vectorA{i} = rand(3); vectorB{i} = rand(3); end timesCross = zeros(N, 1); timesCross3d = zeros(N, 1); for i = 1:N tic(); cross3d(vectorA{i}, vectorB{i}); timesCross3d(i) = toc(); end for i = 1:N tic(); cross(vectorA{i}, vectorB{i}); timesCross(i) = toc(); end disp('Median cross time (vectors from a cell array): '); median(timesCross) disp('Median cross3d time (vectors from a cell array): '); median(timesCross3d)

The scripts were launched from a command line in the following way.

matlab -nojvm -r 'testCrossCell; exit' matlab -nojvm -r 'testCrossMatrix; exit'

The following median time values were obtained.

Script |
cross |
cross3d |

testCrossCell | 1.5772e-05 | 9.7800e-07 |

testCrossMatrix | 1.9430e-06 | 1.8700e-06 |

For the matrix case, there is no significant difference between running times. However, for the cell array case, the running time of `cross3d`

is more than 10 times less than of MATLAB’s native function `cross`

.

To sum up, one should use MATLAB’s `cross`

function for rapid vector product calculation of multiple vector pairs that are known in advance and can be organized into matrices. However, the `cross3d`

function given above may be faster for iterative procedures when a pair of vectors is calculated in each step.