Combine different size matrix
2 次查看(过去 30 天)
显示 更早的评论
I have 4 Matrices (4 is a Value but should be handled as a matrix):
A = [1 1 1;1 1 1;1 1 1];
B = [2 2 2;2 2 2];
C = [3 3 3];
D = [4];
vertcat(A,C,B)
They should be aligned somewhat like this:
syms A
syms B
syms C
syms D
Matrix = [0 D 0 A;0 0 D C;D 0 0 B]
The right side i did with vertcat as shown above. However, i am struggling with Adding D. When its like in the 1. and 3. row, and A/B are 3/2 Row Matrices, D should become a diagonal matrix. Rest filled with 0. When its a single row like C, its just a single Value. So the final result looks like this:
Result = [0 0 4 0 0 0 1 1 1;0 0 0 4 0 0 1 1 1;0 0 0 0 4 0 1 1 1;0 0 0 0 0 4 3 3 3;4 0 0 0 0 0 2 2 2;0 4 0 0 0 0 2 2 2]
It should be done for multiple different cases, so an "automatic" way would be great.
Thank you very much!
0 个评论
采纳的回答
Stephen23
2023-1-9
编辑:Stephen23
2023-1-9
Works for any data sets, you just need to specify the column/row order of the matrices:
C = {[1,1,1;1,1,1;1,1,1];[2,2,2;2,2,2];[3,3,3]}; % matrices A,B,C, ...etc
[~,Xc] = ismember('BAC','ABC'); % col order
[~,Xr] = ismember('ACB','ABC'); % row order
D = 4; % scalar
R = cellfun('size',C,1);
[~,Yr] = sort(repelem(Xr(Xc),R(Xc)));
M = D*eye(sum(R));
M = [M(Yr,:),vertcat(C{Xr})]
0 个评论
更多回答(2 个)
KSSV
2023-1-9
编辑:KSSV
2023-1-9
A = [1 1 1;1 1 1;1 1 1];
B = [2 2 2;2 2 2];
C = [3 3 3];
D = 4;
iwant = [diag(repmat(D,1,4),2) vertcat(A,C,B)] ;
iwant([5 12]) = D
3 个评论
Bjorn Gustavsson
2023-1-9
@Fabian Haslwanter, you should think of the different blocks as individual matrices, and then depending on what ordering you want you should build them the corresponding sizes. If you take an intermediate step for thinking you get:
syms A B C D1 D2 D3 zA1 zA2 zB1 zB2 zC1 zC2
Matrix = [zA1,D1,zA2,A;zB1,zB2,D2,B;D3,zC1,zC2,C];
Frome there you should be able to figure out what lengths you need to expand your scalar (?) D to in the different diagonal-matrices, and what sizes you need for the different zero-blocks. I think I got the first block of rows right in my answer. It should be doable to expand that snippet without too much sweat.
Bjorn Gustavsson
2023-1-9
If your D is a scalar that you want to expand into a diagonal matrix then perhaps you can do something along these lines:
szA = size(A);
szB = size(B);
szC = size(C);
szD = size(D);
Matrix = [zeros(szA(1),szB(2)) diag(repmat(D,szA(1))) zeros(szA(1),szC(2)) A];
and so on for the other rows. It is a bit fidgety, but this should set you on the right path.
HTH
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Linear Algebra 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!