hasdrubal
hasdrubal

Reputation: 1148

Stack submatrices 3d matrix in one matrix

So lets say that I have a 3d matrix A of variable size. Is there an easy to use command that stacks the matrix like B = [squeeze(A(1,:,:)); squeeze(A(2,:,:)); ...; squeeze(A(n,:,:))] ?

Right now I use the following, but its cumbersome:

if(length(A(:,1,1))==1)
    B =squeeze(A);
else
    B = zeros(length(A(:,1,1)*length(A(1,:,1)), length(A(1,1,:)));
    B(1:length(A(1,:,1)),:) = squeeze(A(1,:,:));

    for i=2:length(A(1,:,1)
        B(1:i*length(A(1,:,1)),:)=...
            vertcat(B, squeeze(A(i,:,:)));
    end
end

Upvotes: 1

Views: 52

Answers (3)

TroyHaskin
TroyHaskin

Reputation: 8401

You can use reshape with a permutation of the matrix's dimensions and a transpose:

C = reshape(permute(A,[3,2,1]),size(A,3),[]).';

Which will gracefully adapt to arbitrary row count. A little test:

A = rand([3,4,4]);
B = [squeeze(A(1,:,:)); squeeze(A(2,:,:)); squeeze(A(3,:,:))];
C = reshape(permute(A,[3,2,1]),size(A,3),[]).';
all(B(:)==C(:)) % should be true/1

Upvotes: 4

Divakar
Divakar

Reputation: 221614

Here's one more using permute and reshape -

B = reshape(permute(A,[2,1,3]),[],size(A,3))

Upvotes: 3

Luis Mendo
Luis Mendo

Reputation: 112749

This will do the same as B = [squeeze(A(1,:,:)); squeeze(A(2,:,:)); ...; squeeze(n,:,:))]. Not sure it's faster than the loop:

B = num2cell(A, [2 3]); % split along first dimension into cells 
B = permute([B{:}], [2 3 1]); % concatenate the cells along second dimension
    % and remove first dimension, which is a singleton

Upvotes: 4

Related Questions