MATLAB Tutorial 2
Variables
π and sin() function
In the second example the trigonometric function sine and the constant π are used. In MATLAB
they are named sin and pi, respectively.
fun = sin(pi/4)
fun = 0.7071
Numeric format
format long
changes a current format to the format long. To display more digits of the variable fun type
fun
fun = 0.70710678118655
To change a current format to the default one type
format short
fun
fun = 0.7071
In order to display more digits click on File, select Preferences…, and
next select a format you wish to use
To check your variables and format, type
EDU» whos
Name Size Bytes Class
a 1x1 8 double array
fun 1x1 8 double array
Grand total is 2 elements using 16 bytes
To check current variables, type
EDU» who
Your variables are:
a fun
Graphing
To make a graph of y = sin(t) on the interval t = 0 to t = 10 we do the following:
>> t = 0:.3:10;
>> y = sin(t);
>> plot(t,y)
Graphing with m file
Open File and select New>>m file
Type in the following and save the file as chart1.m
t = 0:.3:10;
y = sin(t);
plot(t,y)
Now click Tools>>Run to execute the m file.
(You should see the graph same as the previous one)
Graphing with two variables
Here is how we graph the function, z(x,y) = x exp( - x^2 - y^2):
Type the following into a m file and run it.
[x,y] = meshgrid(-2:.2:2, -2:.2:2);
z = x .* exp(-x.^2 - y.^2);
surf(x,y,z)
Output:
Exercise:
Plot the function f(x) = sin(x)/x with m file. Use grid command to show grid.
Answer:
x = 0:pi/100:10*pi;
y = sin(x)./x;
plot(x,y)
grid
Sorting
To sort an array in ascending or descending order. Use sort() and descsort().
Example:
a = [5,2,4,1,3]
b=sort(a)
c=descsort(a)
Inline Function
Sometimes it is handy to define a function that will be used during the current MATLAB session
only. MATLAB has a command inline used to define the so-called inline functions in the
Command Window.
Let
f = inline('sqrt(x.^2+y.^2)','x','y')
f =
Inline function:
f(x,y) = sqrt(x.^2+y.^2)
You can evaluate this function in a usual way
f(3,4)
ans = 5
Note that this function also works with arrays. Let
A = [1 2;3 4]
A =
1 2
3 4
and
B = ones(2)
B =
1 1
1 1
Then
C = f(A, B)
C =
1.4142 2.2361
3.1623 4.1231
Max() and Min()
To use the maximum or minimum element value of the C array, type
max(C)
min(C)
Exercise:
Use it in a function
f(y)=max(C)*2 + min(C)
|