Problem

Provide three different methods of generating the matrix a, one method should use the diag() function, one should use the eye function, and one should use the zeros function.

>> a
a =
     2     0     0
     0     2     0
     0     0     2

Solution

MATLAB

Here is the output in MATLAB.

>> a = eye(3,3) * 2
a =
     2     0     0
     0     2     0
     0     0     2
>> d = [2 2 2]
d =
     2     2     2
>> a = diag(d)
a =
     2     0     0
     0     2     0
     0     0     2
>> a = zeros(3,3);
>> a(1,1) = 2;
>> a(2,2) = 2;
>> a(3,3) = 2;
>> a
a =
     2     0     0
     0     2     0
     0     0     2
Python

Similar results can be achieved in Python, by using the same function names as in MATLAB, but via Python’s numpy package.

Comments