Thoth
Thoth

Reputation: 1041

Split a cube in z-axis using borders

I have a 3D-array e.g, A = rand(3,5,10) and I want split it in the z-dimension using specific borders stored into a matrix, e.g, borders = [1 2;3 5;6 10] to get a new matrix (cell):

B = {A(3,5,borders(1,:)), A(3,5,borders(2,:)), A(3,5,borders(3,:))};

Can we do this using a built-in function, i.e, without for loops?

EDIT:

B = cell(1, length(borders));
for i=1:length(borders)
    B{i} = A(:,:, borders (i,1):borders (i,2));
end

Upvotes: 1

Views: 63

Answers (2)

Suever
Suever

Reputation: 65430

You can use borders directly as a index and then use mat2cell to break it into a cell array where each element is [1 x 1 x size(border, 2)].

B = squeeze(mat2cell(A(3,5,borders),1,1,ones(size(borders,1),1)*size(borders,2))).';

The squeeze and transpose are really just to get it to be exactly the same shape as yours, if you don't care about the shape of the resulting cell array you can simply do.

B = mat2cell(A(3,5,borders),1,1,ones(size(borders,1),1)*size(borders,2));

Upvotes: 1

Dominic
Dominic

Reputation: 403

If its not important, that B is a 3d array, this should produce the same result:

reshape(A(3,5,borders(:)), size(borders))

ans =

    0.1419    0.7060
    0.4898    0.3500
    0.0759    0.4173


squeeze(B)

ans =

    0.1419    0.7060
    0.4898    0.3500
    0.0759    0.4173

Upvotes: 1

Related Questions