How to use blkdiag in 3D matrix
조회 수: 3 (최근 30일)
이전 댓글 표시
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
채택된 답변
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
댓글 수: 0
추가 답변 (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{:})
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!