Home > OS >  Matrix operator to stack the rows of a matrix on the "diagonal"
Matrix operator to stack the rows of a matrix on the "diagonal"

Time:05-04

I am looking for a matrix operator (or a mathematical expression) that does the following:

I have a matrix A of dimension 3 by 5:

a_11 a_12 a_13 a_14 a_15
a_21 a_22 a_23 a_24 a_25
a_31 a_32 a_33 a_34 a_35

I want to obtain the matrix 3 by 15:

a_11 a_12 a_13 a_14 a_15 0    0    0    0    0    0    0    0    0    0
0    0    0    0    0    a_21 a_22 a_23 a_24 a_25 0    0    0    0    0
0    0    0    0    0    0    0    0    0    0    a_31 a_32 a_33 a_34 a_35

I have tried to use Kronecker products but I didn't arrive to any solution.

CodePudding user response:

You could solve it using the following:

a = [1,2,3;4,5,6;7,8,9]
sz = size(a) % find the dimensions
m = zeros(sz(1), prod(sz)) %Create a matrix of zeros
for row = 1:sz(1)
    m(row,(1:sz(2))   (row-1) * sz(2)) = a(row,:) %replace each row accordingly
end

m =

     1     2     3     0     0     0     0     0     0
     0     0     0     4     5     6     0     0     0
     0     0     0     0     0     0     7     8     9

CodePudding user response:

Not a matrix-algebra expression, but in case it helps: this can be easily done using num2cell to split the matrix into a cell array of its rows, and passing a comma-separated list of those rows to blkdiag:

A = randi(9,3,5); % example input
A_cell = num2cell(A, 2);
result = blkdiag(A_cell{:});
  • Related