For a tutorial on MATLAB that is calculus specific you can point your
browser at
http://www.math.csi.cuny.edu/MATLAB/tutorial/.
Creating Matrices
To create matrices you designate to MATLAB that you want a matrix with
the square brackets:
,
>> A = [1 2 3 4] % the matrix [1 2 3 4] >> A = [1, 2, 3, 4] % the matrix [1 2 3 4]The same is achieved by putting in commas as the example indicates
>> A = [1 2 ; 3 4] % 2 rows A = 1 2 3 4 >> A = [1 2; 3 4; 5 6] % 3 rows A = 1 2 3 4 5 6 >> A = [1 2 3; 4 5 6] % again 2 rows A = 1 2 3 4 5 6
Notice you need to have the same number of elements in each row
>>A = [1 2 3; 4 5] error: number of columns must match % oops!
Think about the semicolon as joining rows together. For example look at
>> B = [ 1 2 3]; C = [4 5 6]; % no output with the trailing ; >> A = [B ; C] A = 1 2 3 4 5 6
So to paste rows together you use a semicolon.
>> A = [B C] % already defined A = [1 2 3 4 5 6] >> A = [B' C'] % prime is a transpose A = 1 4 2 5 3 6
Here we used the transpose of a matrix which flips the role of rows and columns. For example, with A, B and C as above:
>> A' ans = 1 2 3 4 5 6 >> B' % B was [1 2 3], B' is [1 ; 2 ;3] ans = 1 2 3 >> C' ans = 4 5 6
Let's see how we form an augmented matrix, This joins a column called b to a matrix A. Suppose we start with the system of equations 5x
>> A = [5 6; 4 -7]; % suppress output
The column matrix b contains the constants.
>> b = [7 8]' % notice the transpose
Then we want to join the column vector b to the matrix A by attaching a column
>> A = [A b] A = 5 6 7 4 -7 8
How to access numbers in a MATRIX
>> A(1,1) % gives 5. Notice the parentheses (,) >> A(2,3) % gives 8 >> A(3,2) % an error. No third row
We can also extract slices by putting lists of numbers
>> A([1 2],3) % A(1,3) and A(2,3) ans = 7 8 >> A(2,[1 2]) % A(2,1) and A(2 2) ans = 4 -7
Slices take time to think about.
Here is a side diversion:
Generating numbers
An important command to generate numbers in a systematic way is to use the colon operator. its syntax is
>> a:b % from a to b by 1's >> a:h:b % from a to b by steps of size 'h'
for example the commands below give the output indicated
>> 1:3 % same as [1 2 3] >> 1:2:9 % gives [1 3 5 7 9]
More on slices
We use these to extract parts of matrices.
For example the ones above could be written
>> A(1:2,3) % A(1,3) and A(2,3) ans = 7 8 >> A(2,1:2) % A(2,1) and A(2 2) ans = 4 -7
Finally, there is a shortcut when you want the entire row or column. Just use a semicolon ``:''
>> A(:,2) ans = 6 -7 >> A(2,:) ans = 4 -7 8