Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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