First lesson
Contents
Command window
2+3
ans = 5
2*pi% Pi isn't working, Matlab is case-sensitive
ans = 6.2832
3/exp(1)
ans = 1.1036
An earlier command can't be modified, but with the up arrow (on the keyboard) we can reuse them. Moreover typing the start of command + up arrow brings back only the commands starting with what we typed.
i*3^4
ans = 0.0000 +81.0000i
Assignment
a=5.1
a = 5.1000
a
a = 5.1000
With the command who we can list the name of the assigned variables
who
Your variables are: a ans
With the command whos we get more detailed information
whos
Name Size Bytes Class Attributes a 1x1 8 double ans 1x1 16 double complex
The command clear deletes the value of a variable, (the command clear all deletes all of them, but mostly it's a bad practice to use this command)
clear a
whos
Name Size Bytes Class Attributes ans 1x1 16 double complex
Changing format
We can change the display style, however it doesn't effect the accuracy of our calculations
format short
5.123456789
ans = 5.1235
We get a short description of the command by typing help + name of the command. A more detailed help with examples is available in the documentation, directly available by typing doc + of the command
help format
FORMAT Set output format. FORMAT with no inputs sets the output format to the default appropriate for the class of the variable. For float variables, the default is FORMAT SHORT. FORMAT does not affect how MATLAB computations are done. Computations on float variables, namely single or double, are done in appropriate floating point precision, no matter how those variables are displayed. Computations on integer variables are done natively in integer. Integer variables are always displayed to the appropriate number of digits for the class, for example, 3 digits to display the INT8 range -128:127. FORMAT SHORT and LONG do not affect the display of integer variables. FORMAT may be used to switch between different output display formats of all float variables as follows: FORMAT SHORT Scaled fixed point format with 5 digits. FORMAT LONG Scaled fixed point format with 15 digits for double and 7 digits for single. FORMAT SHORTE Floating point format with 5 digits. FORMAT LONGE Floating point format with 15 digits for double and 7 digits for single. FORMAT SHORTG Best of fixed or floating point format with 5 digits. FORMAT LONGG Best of fixed or floating point format with 15 digits for double and 7 digits for single. FORMAT SHORTENG Engineering format that has at least 5 digits and a power that is a multiple of three FORMAT LONGENG Engineering format that has exactly 16 significant digits and a power that is a multiple of three. FORMAT may be used to switch between different output display formats of all numeric variables as follows: FORMAT HEX Hexadecimal format. FORMAT + The symbols +, - and blank are printed for positive, negative and zero elements. Imaginary parts are ignored. FORMAT BANK Fixed format for dollars and cents. FORMAT RAT Approximation by ratio of small integers. Numbers with a large numerator or large denominator are replaced by *. FORMAT may be used to affect the spacing in the display of all variables as follows: FORMAT COMPACT Suppresses extra line-feeds. FORMAT LOOSE Puts the extra line-feeds back in. Example: format short, pi, single(pi) displays both double and single pi with 5 digits as 3.1416 while format long, pi, single(pi) displays pi as 3.141592653589793 and single(pi) as 3.1415927. format, intmax('uint64'), realmax shows these values as 18446744073709551615 and 1.7977e+308 while format hex, intmax('uint64'), realmax shows them as ffffffffffffffff and 7fefffffffffffff respectively. The HEX display corresponds to the internal representation of the value and is not the same as the hexadecimal notation in the C programming language. See also DISP, DISPLAY, ISNUMERIC, ISFLOAT, ISINTEGER. Reference page in Doc Center doc format
Creating matrices
We can specify the elements of a (row )vector per item: we write the numbers between square bracket separated by space or commas.
v=[1 2 4];
We can also define column vectors, by separating the numbers by semicolon.
w=[5 ; 6 ; -1]
w = 5 6 -1
If we want to define a matrix we separate the rows by a semicolon, hence a matrix is a column vector which elements are row vectors.
C=[1 0 3; 4 3 -1; 3 -5 8]
C = 1 0 3 4 3 -1 3 -5 8
The first row is: 1 0 3.
We can also create matrices using predefined functions like:
A=diag(v)
A = 1 0 0 0 2 0 0 0 4
A matrix, which diagonal is the input vector v.
I=eye(5)
I = 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1
the 5 times 5 identity matrix
Z=zeros(5,2)
Z = 0 0 0 0 0 0 0 0 0 0
a 5 times 2 matrix, which elements are zeros
E=ones(2,3)
% a 2 times 3 matrix, which elements are ones
E = 1 1 1 1 1 1
The size of a matrix:
size(C)
ans = 3 3
number of its rows
size(E,1)
ans = 2
number of its columns
size(E,2)
ans = 3
the maximum of these two quantity:
length(E)
ans = 3
Creating vectors
We can create a row vector by using the : operator. The a:b:c vector starts with a, its stepsize is b and its last item isn't greater than c.
x=0:0.3:1
x = 0 0.3000 0.6000 0.9000
Let's check the size
whos
Name Size Bytes Class Attributes A 3x3 72 double C 3x3 72 double E 2x3 48 double I 5x5 200 double Z 5x2 80 double ans 1x1 8 double v 1x3 24 double w 3x1 24 double x 1x4 32 double
An other way to create vectors is by using the linspace command. linspace(1,2) is a vector, its first element is 1, its last is 2, has equal stepsize and 100 elements. We can also specify the number of element with a third input value.
y_sor=linspace(1,2,5)
y_sor = 1.0000 1.2500 1.5000 1.7500 2.0000
Keep in mind, that row and column vectors can't be exchanged in calculation.
Indexing
We can index the element of vectors with (), the first item of vector v is v(1).
x(1) x(2)
ans = 0 ans = 0.3000
be careful x(6), doesn't exists, however we can assign value to it:
x(10)=5
x = Columns 1 through 7 0 0.3000 0.6000 0.9000 0 0 0 Columns 8 through 10 0 0 5.0000
Although x had only four items, now thanks to our assignment command it has 10 itemes, the ones we haven't gives values are zeros.
We can index matrices by using two numbers: the first one is the number of the rows, the second one is the number of the columns
C(3,2)
ans = -5
However, we can use only one number for indexing matrices:
C(6)
ans = -5
for this particular matrix, this is the same as C(3,2), because if we use one number to index a matrix then Matlab goes through the columns.
We can do some nice tricks with indexing. This is the first row:
C(1,:)
ans = 1 0 3
2 times 2 minor
C(1:2,1:2)
ans = 1 0 4 3
Every second column:
C(:,1:2:3)
ans = 1 3 4 -1 3 8
Operation
x_sor=0:0.3:1
x_sor = 0 0.3000 0.6000 0.9000
How many item does x_sor have?
length(x_sor)
ans = 4
transpose (in fact conjugate transpose)
x_oszlop=x_sor'
x_oszlop = 0 0.3000 0.6000 0.9000
The sizes doesn't match, hence you can't add them element wise.
size(x_sor)
ans = 1 4
size(x_oszlop)
ans = 4 1
Multiplying by constant
5*x
ans = Columns 1 through 7 0 1.5000 3.0000 4.5000 0 0 0 Columns 8 through 10 0 0 25.0000
Dot product (a real number!)
x_sor*x_sor'
ans = 1.2600
alternatively
dot(x_sor,x_sor)
ans = 1.2600
Dyadic product (a matrix)
D=x_sor'*x_sor
D = 0 0 0 0 0 0.0900 0.1800 0.2700 0 0.1800 0.3600 0.5400 0 0.2700 0.5400 0.8100
Elementwise square.
x_sor.*x_sor
ans = 0 0.0900 0.3600 0.8100
In general dot means: element wise
x_sor.^2+3*x_sor+sin(x_sor)./cos(x_sor)
ans = 0 1.2993 2.8441 4.7702
The Matlab has a wide varety of build-in functions, most of them is polymorphic. For example the smallest element of a vector is:
min(x_sor)
ans = 0
but if we are interested in the values and the position of the smallest element, then:
[minertek,minpozicio]=min(x_sor)
minertek = 0 minpozicio = 1
Try not to redefine these functions!
Editor
We can write custom functions. Let us open an editor window. In the first row comes the function's declaration statement: the number and name(s) of the output(s) and input(s), if there is any.
function output=functionname(input)
or function [outputs separated by comas]=functionname(inputs separated by comas)
In the second row we can write an optional help after a %
Then we write our commands. At last we have to save our work in a file, which extension has to be .m.
Make sure the the filename matches the function name (this is strongly recommended, although Matlab doesn't gives us an error if they don't match).
Let us see an example
function w=firstitem(v) % The output is the first element of and array. % usage: firstelement(v), where v is a vector w=v(1);
We can use our newly written function by typing its name in the command window (actually the file's name without the .m, not the function's name, but since they are the same...)
firstitem([-1 0 2 3])
ans = -1
every variable inside the function is local, that is after the running we can't access it's value.
Our short description is available for any user by typing help and the name of our function
help firstitem
The output is the first element of and array. usage: firstelement(v), where v is a vector
Our next example is a function with two outputs: the upper left and the lower right item of a matrix
function [uleft, lright]=corners(A) % The outputs are the upper left and lower right item of the input matrix % Usage: [ule, lri]=corners(A), where A is a matrix uleft=A(1,1); lright=A(end, end);
We can use this function by defining two variables
[bf, ja]=corners(D)
bf = 0 ja = 0.8100
However it still works if we just write
corners(D)
ans = 0
but it gives only the first output
Recommended problems (with solutions)
1. Problem: Write a function called pitThe, that takes has two column vector input argument. The inputs are cathetuses of right triangles and the output is the hypotenuse of these triangles.
The .m file
function hypet=pitThe(cat1,cat2)
hypet=sqrt(cat1.^2+cat2.^2);
Testing in the command window:
pitThe([3;5],[4;12])
ans = 5 13
2. Problem: Write a function terjD, that takes a vector input argument and returns the difference between v's smallest and biggest element.
function ki=terjD(v)
ki=min(v)-max(v);
4. Problem: Write a function called strangeMatrix that takes a positive integer input argument, say n, and returns a 2n times 2n matrix. The upper left n times n corner of the output contains ones, the upper right threes, the lower left twos and the lower right zeros.
function strangem=strangeMatrix(n)
strangem=zeros(2*n);
strangem(1:n,1:n)=1;
strangem(1:n,n+1:2*n)=3;
strangem(n+1:2*n,1:n)=2;
6. Problem: Write a function called oddMax that takes a matrix input argument, and returns the maximum of the elements being in an odd row.
function oddm=oddMax(A)
oddm=max(max(A(1:2:end, :)));
Optional homework
3. Problem: Write a function called upperLeft, that takes a matrix and a positive integer, (say n) input argument and returns the n times n minor of the matrix.
function mi=upperLeft(A,n)
mi=A(1:n,1:n);
5. Problem: Write a function called chessTable that takes a positive integer input argument, say n, and returns a n times n matrix, which elements are zeros or ones. The upper left element of the output matrix is 1, the adjacent elements are different.
function cht=chessTable(n)
cht=zeros(n);
cht(1:2:end,1:2:end)=1;
cht(2:2:end,2:2:end)=1;