Advertisement
gaetawoo

MATLAB mid.m midpoint function

Jun 16th, 2019
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 2.00 KB | None | 0 0
  1. function indices = mid(data, opt_dimension)
  2.   %%INDICES = MID(DATA, OPT_DIMENSION)
  3.   %
  4.   %  Returns midpoint index values.
  5.   %    -If dimension is specified, returns single-dimensional index(es) of the midpoint of that
  6.   %    dimension.
  7.   %    -If dimension is not specified, returns array-wide index(es) of the midpoint of the entire
  8.   %    multidimensional array.
  9.   %    -If elements along a given dimension are even in number, then central two indices
  10.   %    will be returned.
  11.   %
  12.   % By Jeremiah J. Valenzuela
  13.   % June 15, 2019
  14.  
  15.   % Check if dimension argument has been passed in
  16.   if exist('opt_dimension', 'var')
  17.     dimsize = size(data, opt_dimension);
  18.     if mod(dimsize, 2) % is odd
  19.       indices = ceil(dimsize / 2);
  20.     else % is even
  21.       indices = [dimsize / 2;
  22.                  dimsize / 2 + 1];
  23.     end
  24.    
  25.   else
  26.     % Initialize main variables
  27.     nDimensions = size(size(data), 2); % Number of dimensions
  28.     nIndices = 2^sum(abs(mod(size(data), 2) - 1), 'all'); % Compute total number of midpoints
  29.     indices = zeros(nIndices, 1);
  30.     midSubscripts = zeros(nIndices, nDimensions);
  31.     nTwoElementVectors = 0;
  32.     for iDim = 1:nDimensions
  33.       tempSubscripts = mid(data, iDim); % Recursive call with dimensional argument
  34.       if size(tempSubscripts, 1) > 1 % If 2 subscript column vector returned
  35.         nTwoElementVectors = nTwoElementVectors + 1;
  36.         % Arrange corresponding subscripts so ever possibly point combination is created
  37.         midSubscripts(1:nIndices, iDim) = reshape(reshape(kron(tempSubscripts',ones(nIndices / 2, 1)), 2^(nTwoElementVectors - 1), [])', [], 1);
  38.       else % If single subscript is returned
  39.         midSubscripts(1:nIndices, iDim) = tempSubscripts;
  40.       end
  41.     end
  42.    
  43.     % Convert each row of subscripts into an index of the point relative to the full array
  44.     for iPoint = 1:nIndices
  45.       cellSubscripts = num2cell(midSubscripts(iPoint, :));
  46.       indices(iPoint, 1) = sub2ind(size(data), cellSubscripts{:});
  47.     end
  48.   end
  49. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement