MATLAB: Generate a diagonal matrix from the elements of another matrix

diagonal matrixMATLABmatrixmatrix manipulation

Good morning, I'm trying to generate a diagonal matrix with non-zero elemets from another matrix.
For example I have a general matrix like: (usually it's around 40×5)
A=[1 2 3 4 5;
6 7 8 9 10];
I would like to generate a matrix with the elements of A on the diagonal, just like:
1 0 0 0 0 0 0 0 0 0
0 2 0 0 0 0 0 0 0 0
0 0 3 0 0 0 0 0 0 0
0 0 0 4 0 0 0 0 0 0
0 0 0 0 5 0 0 0 0 0
0 0 0 0 0 6 0 0 0 0
And so on untili 10.
Can someone help me?
Thanks in advance

Best Answer

I would recommend using diag function.
The following is an example:
A = [1 2 3 4 5;
6 7 8 9 10];
A = A';
output = diag(A(:));
>> output
output =
1 0 0 0 0 0 0 0 0 0
0 2 0 0 0 0 0 0 0 0
0 0 3 0 0 0 0 0 0 0
0 0 0 4 0 0 0 0 0 0
0 0 0 0 5 0 0 0 0 0
0 0 0 0 0 6 0 0 0 0
0 0 0 0 0 0 7 0 0 0
0 0 0 0 0 0 0 8 0 0
0 0 0 0 0 0 0 0 9 0
0 0 0 0 0 0 0 0 0 10