0

I want to extract a 2D matrix from a 3D matrix. Now, I know how to do it with

A = ones(10,10,10);
B = squeeze(A(:,:,2));

But I want to write a function which will get as inputs the 3D matrix, and the dimension and index where to get the 2D matrix. In the example above, this would give:

B = my_func(A,3,2);

Any ideas?

Thanks a lot!

  • This has already been answered. Check the duplicate. I've also made an extension which can be applied to multiple dimensions, not just a single dimension: http://stackoverflow.com/questions/27969296/dynamic-slicing-of-matlab-array/27975910#27975910 – rayryeng Jan 30 '15 at 16:41

2 Answers2

1
function out=my_func(A,dim,ix)
    index=repmat({':'},1,ndims(A));
    index{dim}=ix;
    out=squeeze(getfield(A,index));
end

Or another alternative:

function out=my_func(A,dim,ix)
    index=arrayfun(@(x)(1:x),size(A),'uni',false);
    index{dim}=ix;
    out=squeeze(A(index{:}));
end
Daniel
  • 36,610
  • 3
  • 36
  • 69
0

How about:

function out=my_func(A,dim,i)

switch dim
    case 1
        out = squeeze(A(i,:,:));
    case 2
        out = squeeze(A(:,i,:));
    case 3
        out = squeeze(A(:,:,i));
end
Ratbert
  • 5,463
  • 2
  • 18
  • 37
  • Yeah, thought of that, but I was wondering if there was a more streamlined solution without enumerating every possible case... – Gordon Freeman Jan 30 '15 at 16:18