MATLAB: How to generate the matrix of (50,100) with its diagonal alone having values

matrix generation

how to generate the matrix of (50,100) with its diagonal alone having values

Best Answer

Method one: indexing:
M = zeros(50,100);
M(1:51:50^2) = V % vector V must have 50 elements
A simple example:
>> M = zeros(5,10);
>> M(1:6:25) = 1:5
M =
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
Method two: diag:
[diag(V),zeros(50)] % vector V has 50 elements
and an example:
>> [diag(1:5),zeros(5)]
ans =
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