Created
July 19, 2012 00:10
-
-
Save michael-nischt/3139853 to your computer and use it in GitHub Desktop.
accessing a sub-matrix of an unknown multi-dimensional matrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% 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