How to use blkdiag in 3D matrix

6 Ansichten (letzte 30 Tage)
KostasK
KostasK am 15 Okt. 2020
Beantwortet: madhan ravi am 15 Okt. 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.

Akzeptierte Antwort

Ameer Hamza
Ameer Hamza am 15 Okt. 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

Weitere Antworten (1)

madhan ravi
madhan ravi am 15 Okt. 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{:})

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by