create a=[1 0; 0 1] and multiply it with b=[2 1; 4 0] in matlab

To create a matrix in Matlab, the elements should be wrapped in square brackets []. To create a 2x2 identity matrix, we can use the built-in function eye() as follows:

main.m
a = eye(2); 
13 chars
2 lines

gives

main.m
a = 

     1     0
     0     1
32 chars
5 lines

To multiply a with b, we use the * operator. Hence, the code would look like this:

main.m
a = [1 0; 0 1];
b = [2 1; 4 0];
c = a * b;
43 chars
4 lines

gives

main.m
c =

     2     1
     4     0
31 chars
5 lines

Alternatively, we can use the mtimes() function to get the same result:

main.m
c = mtimes(a,b);
17 chars
2 lines

which also gives the same result:

main.m
c =

     2     1
     4     0
31 chars
5 lines

related categories

gistlibby LogSnag