create a function that rotates an n-dimensional array about a specified axis in matlab

Here's an example function that rotates an nD array about a specified axis:

main.m
function rotatedArray = rotateNDArray(array, axis, angle)
  if numel(size(array)) <= axis
    error("Specified axis is greater than the number of dimensions in the array")
  end

  % Create a cell array with ':' for each dimension
  % Set the desired dimension to 1:sz, where sz is the size of that dimension
  subscripting = cell(1, numel(size(array)));
  subscripting(:) = { ':' };
  subscripting{axis} = 1:size(array,axis);

  % Create a list of subscripts for the array
  subscripts = cell(1, numel(size(array)));
  [subscripts{:}] = ndgrid(1:size(array,1), 1:size(array,2), 1:size(array,3));

  % Convert the cell array to a comma-separated list
  subscriptList = [subscripts{:}];
  % Adjust the subscript list to match the desired axis
  subscriptList = subscriptList(:, axis);

  % Compute the rotation matrix
  rotationMatrix = getRotationMatrix(size(array, axis), angle);

  % Apply the rotation to the subscript list
  rotatedSubscripts = subscriptList * rotationMatrix;

  % Reshape the subscript list into a cell array
  subsCell = num2cell(rotatedSubscripts, 1);

  % Combine the indexing cell array and the subscript cell array
  indexingCell = [subscripting; subsCell];

  % Use the combined cell array to index into the array
  rotatedArray = array(indexingCell{:});
end


function R = getRotationMatrix(n, angle)
  % Compute the rotation matrix - this is just for 2D or 3D arrays
  if n == 2
    R = [cosd(angle), -sind(angle); sind(angle), cosd(angle)];
  elseif n == 3
    R = [cosd(angle), -sind(angle), 0; sind(angle), cosd(angle), 0; 0, 0, 1];
  else
    % generalization of 2D and 3D rotation about x axis
    R = zeros(n,n);
    R(1,1) = 1;
    R(n,n) = 1;
    R(2:n-1, 2:n-1) = getRotationMatrix(n-2, angle);
  end
end
1744 chars
52 lines

To use this function, pass in the nD array, the desired axis (as an integer), and the rotation angle (in degrees):

main.m
% Create a 3D array
array = eye(3,3,3);

% Rotate the array about the third axis
rotatedArray = rotateNDArray(array, 3, 90);
125 chars
6 lines

This will rotate the 3D identity matrix by 90 degrees about the third axis.

gistlibby LogSnag