# Lesson 2: Entering matrices

 MATLAB works with essentially only one kind of object, ie. a rectangular numerical matrix with possibly complex entries; all variables represent matrices. In some situations, 1-by-1 (1 x 1) matrices are interpreted as scalars and matrices with only one row (1 x n) or one column (m x 1) are interpreted as vectors. Matrices can be introduced into MATLAB in several different ways: Entered by an explicit list of elements Created in M-files Loaded from external data files (see User's Guide) Generated by built-in statements and functions For example, either of the statements ``` A = [1 2 3; 4 5 6; 7 8 9] ``` and ``` A = [ 1 2 3 4 5 6 7 8 9 ] ``` creates the obvious 3-by-3 matrix and assign it to a variable A. Try it! The elements with a row of a matrix may be seperated by commas as well as a blank. So the above statements are the same as: ``` A = [1,2,3; 4,5,6; 7,8,9] ``` and ``` A = [ 1,2,3 4,5,6 7,8,9 ] ``` When listing a number in exponential form (eg. 1.23e-4), blank spaces must be avoided. Listing entries of a large matrix is best done in an M-file or an ASCII file, where errors can be easily edited away. ASCII files should contain a rectangular array of just the numeric matrix entries. If this file is named, say, data.ext (where .ext is any extension), the MATLAB command load data.ext will read this file to the variable data in your MATLAB workspace. The built-in functions rand, magic and hilb, for example, provide an easy way to create matrices with which to experiment. The command rand(n) will create an n × n matrix with randomly generated entries distributed uniformly between 0 and 1, while rand(m,n) will create an m × n one. magic(n) will create an integral n × n matrix which is a magic square (rows and columns have common sum); hilb(n) will create the n × n Hilbert matrix, the king of ill-conditioned matrices (m and n denote positive integers). Matrices can also be generated with a for-loop. Individual matrix and vector entries can be referenced with indices inside parentheses in the usual manner. For example, A(1,2) denotes the entry in the first row, second column of matrix A and x(3) denotes the third coordinate of vector x. Try it! A matrix or a vector will only accept positive integers as indices.