CROSSPRODUCT3D Vector cross product faster than inbuilt MATLAB cross. C = crossProduct3d(A, B) returns the cross product of the two 3D vectors A and B, that is: C = A x B A and B must be N-by-3 element vectors. If either A or B is a 1-by-3 row vector, the result C will have the size of the other input and will be the concatenation of each row's cross product. Example v1 = [2 0 0]; v2 = [0 3 0]; crossProduct3d(v1, v2) ans = 0 0 6 Class support for inputs A,B: float: double, single See also DOT.
0001 function c = crossProduct3d(a,b) 0002 %CROSSPRODUCT3D Vector cross product faster than inbuilt MATLAB cross. 0003 % 0004 % C = crossProduct3d(A, B) 0005 % returns the cross product of the two 3D vectors A and B, that is: 0006 % C = A x B 0007 % A and B must be N-by-3 element vectors. If either A or B is a 1-by-3 0008 % row vector, the result C will have the size of the other input and will 0009 % be the concatenation of each row's cross product. 0010 % 0011 % Example 0012 % v1 = [2 0 0]; 0013 % v2 = [0 3 0]; 0014 % crossProduct3d(v1, v2) 0015 % ans = 0016 % 0 0 6 0017 % 0018 % 0019 % Class support for inputs A,B: 0020 % float: double, single 0021 % 0022 % See also DOT. 0023 0024 % Sven Holcombe 0025 0026 % HISTORY 0027 % 2017-11-24 rename from vectorCross3d to crossProduct3d 0028 0029 % size of inputs 0030 sizeA = size(a); 0031 sizeB = size(b); 0032 0033 % Initialise c to the size of a or b, whichever has more dimensions. If 0034 % they have the same dimensions, initialise to the larger of the two 0035 switch sign(numel(sizeA) - numel(sizeB)) 0036 case 1 0037 c = zeros(sizeA); 0038 case -1 0039 c = zeros(sizeB); 0040 otherwise 0041 c = zeros(max(sizeA, sizeB)); 0042 end 0043 0044 c(:) = bsxfun(@times, a(:,[2 3 1],:), b(:,[3 1 2],:)) - ... 0045 bsxfun(@times, b(:,[2 3 1],:), a(:,[3 1 2],:));