Skip to content

Instantly share code, notes, and snippets.

@schluppeck
Created November 12, 2019 18:02
Show Gist options
  • Save schluppeck/430e49f4c9b90e3d6bca40f52afa6dee to your computer and use it in GitHub Desktop.
Save schluppeck/430e49f4c9b90e3d6bca40f52afa6dee to your computer and use it in GitHub Desktop.
2019 solution to the returnSlice() matlab problem
function s = returnSlice(array, sliceNum, orientation)
% returnSlice - return a 2d slice from a 3d array in given orientation
%
% ds, 2019-11-05, for matlab class
% add some reality check about sizes... just in case
% potential problem: user can ask for sliceNum that goes beyond size of
% array
% find out sizes of the data cube
% then index into the appropriate orientation.
% THIS GIVES the maximum slice number we don't want to exceed
sz = size(array);
sz( orientation );
% this version just ask for the size in particular orientation..
if sliceNum > size(array, orientation)
error('UHOH! asking for a slice# too high')
% then we are in trouble
end
% let's assume orientation is set to 1 by user
% given a 3d cube of data: array and sliceNum select out some data
if orientation == 1
% do one thing
disp('the value of ORIENTATION was 1')
s = array(sliceNum, :,: );
elseif orientation == 2
% do the other thing
s = array(:, sliceNum, : );
elseif orientation == 3
% third way of slicing
s = array(: , :, sliceNum );
else
error('orientation needs to be 1, 2, or 3');
end
% make sure 's' is returned.
% deal with weird singleton dimensions
s = squeeze(s);
end % ends function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment