Combine different size matrix
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Fabian Haslwanter
le 9 Jan 2023
Commenté : Fabian Haslwanter
le 9 Jan 2023
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 commentaires
Réponse acceptée
Stephen23
le 9 Jan 2023
Modifié(e) : Stephen23
le 9 Jan 2023
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 commentaires
Plus de réponses (2)
KSSV
le 9 Jan 2023
Modifié(e) : KSSV
le 9 Jan 2023
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 commentaires
Bjorn Gustavsson
le 9 Jan 2023
@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
le 9 Jan 2023
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 commentaires
Voir également
Catégories
En savoir plus sur Linear Algebra dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!