>> a = [1,2,3; 4 5 6]Note that:
>> a(1,2), a(2,3)It's very easy to modify matrices:
>> a(2,3) = 10The transpose of a matrix is the result of interchanging rows and columns. Matlab denotes the transpose by following the matrix with the single-quote [apostrophe].
>> a' >> b=[1 1 1]'New matrices may be formed out of old ones, in many ways. Enter the following commands; before pressing the enter key, try to predict their results!
>> c = [a; 7 8 9] >> [a; a; a] >> [a, a, a] >> [a', b] >> [ [a; a; a], [b; b] ]There are many built-in matrix constructions. Here are a few:
>> rand(1,3), rand(2) >> zeros(3) >> ones(3,2) >> eye(3), eye(2,3) >> magic(3) >> hilb(5)This last command creates the 5 by 5 "Hilbert matrix," a favorite example.
Use a semicolon to suppress output:
>> s = zeros(20,25);
This is valuable, when working with large matrices. If you forget it,
and
start printing screenfuls of unwanted data, Control-C is Matlab's
"break"
key.
To get more information on these, look at the help pages for elementary and special matrices.
>> help elmat >> help specmatA central part of Matlab syntax is the "colon operator," which produces a list.
>> -3:3The default increment is by 1, but that can be changed.
>> x = -3 : .3 : 3This can be read: "x is the name of the list, which begins at -3, and whose entries increase by .3, until 3 is surpassed." You may think of x as a list, a vector, or a matrix, whichever you like.
You may wish use this construction to extract "subvectors," as follows.
>> x(2:12) >> x(9:-2:1)See if you can predict the result of the following.
>> x=10:100; >> x(40:5:60)The colon notation can also be combined with the earlier method of constructing matrices.
>> a = [1:6 ; 2:7 ; 4:9]A very common use of the colon notation is to extract rows, or columns, as a sort of "wild-card" operator which produces a default list. The following command produces the matrix a, followed by its first row [with all of its columns], and then its second column [with all of its rows].
>> a, a(1,:), a(:,2)
>> s = rand(20,5); s(6:7, 2:9)
Matrices may also be constructed by programming. Here is an example, creating
a "program loop."
>> for i=1:10, >> for j=1:10, >> t(i,j) = i/j; >> end >> endThere are actually two loops here, with one nested inside the other; they define t(1,1), t(1,2), t(1,3) ... t(1,10), t(2,1), t(2,2) ... , t(2,10), ... t(10,10) [in that order].
>> t