How to use blkdiag in 3D matrix

6 views (last 30 days)
KostasK
KostasK on 15 Oct 2020
Answered: madhan ravi on 15 Oct 2020
Hi all,
I would like to know how I can use the blkdiag function for the case of a 3D matrix. In specific, what I mean is the following:
Lets say I have the two following 3D matrices
A(:,:,1) =
1 1 1
1 1 1
1 1 1
A(:,:,2) =
2 2 2
2 2 2
2 2 2
%================
B(:,:,1) =
3 3 3
3 3 3
3 3 3
B(:,:,2) =
4 4 4
4 4 4
4 4 4
And I would like to convert those to some matrix D such that blkdiag(A,B) would give the following:
D(:,:,1) =
1 1 1 0 0 0
1 1 1 0 0 0
1 1 1 0 0 0
0 0 0 3 3 3
0 0 0 3 3 3
0 0 0 3 3 3
D(:,:,2) =
2 2 2 0 0 0
2 2 2 0 0 0
2 2 2 0 0 0
0 0 0 4 4 4
0 0 0 4 4 4
0 0 0 4 4 4
However I find that when trying to use the blkdiag function in such context I get an error. Any other thoughts for a work around?
Thanks for your help in advance.

Accepted Answer

Ameer Hamza
Ameer Hamza on 15 Oct 2020
Try this
A = cat(3, 1*ones(3), 2*ones(3));
B = cat(3, 3*ones(3), 4*ones(3));
C = {A, B}; % combine all matrices in a cell array for easy processing
[rows, cols, pages] = cellfun(@size, C);
M = zeros(sum(rows), sum(cols), pages(1));
for i = 1:pages(1)
C_ = cellfun(@(x) {x(:,:,i)}, C);
M(:,:,i) = blkdiag(C_{:});
end

More Answers (1)

madhan ravi
madhan ravi on 15 Oct 2020
A slight variation:
M = cell(size(B, 3), 1);
for k = 1 : size(A, 3)
M{k} = blkdiag(A(:, : , k), B(:, :, k));
end
M = cat(3, M{:})

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!