How to use blkdiag in 3D matrix
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
KostasK
el 15 de Oct. de 2020
Respondida: madhan ravi
el 15 de Oct. de 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.
0 comentarios
Respuesta aceptada
Ameer Hamza
el 15 de Oct. de 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
0 comentarios
Más respuestas (1)
madhan ravi
el 15 de Oct. de 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{:})
0 comentarios
Ver también
Categorías
Más información sobre Matrices and Arrays en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!