# How to use blkdiag in 3D matrix

2 ビュー (過去 30 日間)
KostasK 2020 年 10 月 15 日

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?

サインインしてコメントする。

### 採用された回答

Ameer Hamza 2020 年 10 月 15 日
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

サインインしてコメントする。

### その他の回答 (1 件)

madhan ravi 2020 年 10 月 15 日
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{:})

サインインしてコメントする。

### Community Treasure Hunt

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

Start Hunting!

Translated by