Skip to content

Instantly share code, notes, and snippets.

@michael-nischt
Created July 19, 2012 00:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michael-nischt/3139853 to your computer and use it in GitHub Desktop.
Save michael-nischt/3139853 to your computer and use it in GitHub Desktop.
accessing a sub-matrix of an unknown multi-dimensional matrix
% if ndims(A) == 3
% submat(A,i) = A(:,:,i)
% alternative use:
% submat(A,i:j) = A(:,:,i:j)
function B = submat( A, i )
s = size(A);
if( length(i) > 1 )
len = prod(size(i));
B = [];
for j = 1:len
B = [B, submat(A, i(j)) ];
end
shape = s;
shape(end) = [];
shape = [shape, len];
B = reshape(B, shape);
return
end
if ( i < 1 || i > s(end) )
error('Index exceeds matrix dimensions.')
end
shape = s(1:end-1);
num = prod( shape );
from = (i-1)*num;
to = from+num;
B = A ( 1+from:to );
if length(shape) == 1
% don't transpose if imput is a 1-d matrix
if s(1) ~= 1 && s(2) ~= 1
B = B';
end
else
B = reshape(B , shape);
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment