Matrices


>> A matrix is a two-dimensional array of numbers. Vectors are special cases of matrices having one row or one column.


>> In MATLAB, you create a matrix by entering elements in each row as comma or space delimited numbers and using semicolons to mark the end of each row. For example, let us create a 4-by-5 matrix a:




>> If the matrix is small you can type it row by row, separating the elements in a given row with spaces or commas and separating the rows with semicolons. For example, typing

A = [2,4,10;16,3,7];



Remember, spaces or commas separate elements in different columns, whereas semicolons separate elements in different rows.


>> To create matrices from Vectors suppose a = [1,3,5] and b = [7,9,11] (row vectors). Note the difference between the results given by [a b] and [a;b] in the following session:




You need not use symbols to create a new array. For example, you can type


D = [[1,3,5];[7,9,11]];


Referencing the Elements of a Matrix:


To reference an element in the mth row and nth column, of a matrix mx, we write:


mx(m, n);



For example, to refer to the element in the 2nd row and 5th column, of the matrix a, as created in the last section, we type:




To reference all the elements in the mth column we type A(:,m).



Let us create a column vector v, from the elements of the 4th row of the matrix a:



You can also select the elements in the mth through nth columns, for this we write:


a(:,m:n)




In the same way, you can create a sub-matrix taking a sub-part of a matrix.




n the same way, you can create a sub-matrix taking a sub-part of a matrix.


For example, let us create a sub-matrix sa taking the inner subpart of a:


3     4     5     

4     5     6     


To do this, write:



Array addressing:


The colon operator selects individual elements, rows, columns, or ''subarrays'' of arrays. Here are some examples: 

v(:) = represents all the row or column elements of the vector v. 

v(2:5) = represents the second through fifth elements; that is v(2), v(3), v(4), v(5). 


A(:,3) = denotes all the elements in the third column of the matrix A. 


A(:,2:5) = denotes all the elements in the second through fifth columns of A. 


A(2:3,1:3) = denotes all the elements in the second and third rows that are also in the first through third columns.


Examples:


Try these operation yourself.

>> a= [4 5 6; 1 2 3; 7 8 9] 
>> a(:) 
>> a= [4 5 6; 1 2 3; 7 8 9] 
>> a(2:5) 
>> a(: , 3) 
>> a= [4 5 6; 1 2 3; 7 8 9] 
>> a(: , 2:3) 
>> a(: , 2:5) 

Output…….?



Deleting a Row or a Column in a Matrix:

You can delete an entire row or column of a matrix by assigning an empty set of square braces [ ] to that row or column. Basically, [ ] denotes an empty array.



For example, let us delete the fourth row of a:



Next, let us delete the fifth column of a:




Example:


In this example, let us create a 3-by-3 matrix m, then we will copy the second and third rows of this matrix twice to create a 4-by-3 matrix.