function C = twobytwoarraymult(A,B) %either A and B should be 2x2 matrices. either or both can be a 2x2xn matrix array, %but if both are arrays, they must have the same n. Output %will be matrix multiplication of 2x2 matrices along 3rd dimentsion in A and B. %either A or B will be broadcast in 3rd dimension if it is only a single matrix, %otherwise it needs to be the same size as A. %will work for higher dimensions than three. the : will recast them as 3D arrays for %the multiply, and C will be returned with the intended multidimensional size. if (ndims(A)>=ndims(B)) C = zeros(size(A)); else C = zeros(size(B)); end C(1,1,:) = A(1,1,:).*B(1,1,:) + A(1,2,:).*B(2,1,:); C(1,2,:) = A(1,1,:).*B(1,2,:) + A(1,2,:).*B(2,2,:); C(2,1,:) = A(2,1,:).*B(1,1,:) + A(2,2,:).*B(2,1,:); C(2,2,:) = A(2,1,:).*B(1,2,:) + A(2,2,:).*B(2,2,:); end