MATLAB-Fall 11-12 Introduction To MATLAB Part I
MATLAB-Fall 11-12 Introduction To MATLAB Part I
Matlab
is a commercial "Matrix Laboratory" package which operates as an interactive programming environment. performance language for technical computing. High level matrix/array language
High
Integrates:
Has
a family of toolboxes.
3
Note: The up-arrow key will display previous commands. When you back up to a previous command that you want to use, hit Enter and it will execute. You can also edit it when you get to it (use the left and right arrows , and modify the command), then execute it.
The
Note: You may sometimes have the current directory instead of the workspace where you can find all the files contained in the indicated path.
The
Note: You can delete some of the non important commands in the command history or clear the entire command history by right clicking on the commands in the command history
6
Variables in Matlab are not declared but they are directly assigned Assignment statement : Variable = number (or expression) num = 6; % assignment only num = 6 % assignment & display Variable names: Must start with a letter May contain letters, digits and underscore Matlab is case sensitive Clear all: command removing all variables, functions, from memory, leaving the workspace empty. clc: Command clearing "clean screen. the command Window only, giving a
7
pi:
= 3.1415926
eps: =2.2204e-016 (smallest amount by which 2 numbers can differ) Inf or inf : , infinity
NaN or nan: not-a-number (results from operations which have undefined numerical results)
ans (The variable ans will keep track of the last output which was not assigned to another variable. ) If you create a variable with the same name of a built-in variable then you cannot refer to the built in variable unless you delete the variable that you created.
digits by default, but always stores numbers and computes to the equivalent of 16 decimal digits (IEEE double precision).
(However, one can convert to single precision: single(pi) returns 3.141593)
format short (fixed point format, with 4 digits after the decimal point, rounding to
the closest),
format long (fixed point format, with 15 digits after the decimal point) format short e, format long e (same as above but in floating point format) format short g, format long g (best of fixed or floating point format)
factorial(n): returns the value of n! fix(x): returns the integral part of x fix(D/d): returns the integral part of the quotient of the division of D by d. rem(a,b): returns the remainder of the division of a by b
9
disp(): displays the content of the quotations disp(X) displays the variable X, without printing its name.
Another way to display X is to type its name, but this prints a leading X=.
>> disp(s) returns: +3.14159e+00 >> disp(s) returns: +7.34 >> disp(s) returns: +3.14159 +2.71828 +1.41421
10
Arithmetic:
+-*/^
Relational:
Logical:
& and, | or
11
the brackets Write inside the brackets the elements of the vector separate them using EMPTY SPACE or a COMMA Example: v =[1 2 5 4]
the brackets Write inside the brackets the elements of the vector separate them using SEMICOLON. Example: v =[1;2;5;4]
12
x=a:c
The first element is a The last element is c The difference between any 2 consecutive values is 1
x=a:b:c
The first element is a The last element is c The difference between any 2 consecutive values is b
13
x(i): returns the ith element of the vector x. x(i:j): returns the elements of vector x from index i to index j. x(end): returns the last element of x length(x): returns the # of elements in x sort(x) : returns a vector whose components are those of x sorted from the smallest to the greatest. y :returns the transpose of y.
14
x([i j]) = x([j i]) : permutes the ith and jth components of a row vector x. x = [x 3]: adds one element 3 at the end of a row vector. x = [10 x]: adds one element 10 at the beginning of a row vector. z = [x y] : generates a new row vector z by concatenating the elements of 2 row vectors x and y.
sum(x): returns the sum of the elements of the vector x. prod(x): returns the product of the elements of the vector x. diff(x) : returns the vector [x(2)-x(1), x(3)-x(2), , x(n)-x(n-1)]. If length(x) = n, then length(diff(x)) = n-1. Maxvalue = max(x): returns the greatest element in the vector x. [Maxvalue pos] = max(x): returns the greatest element in the vector x and its position.
i.e. returns i such that x(i) = Maxvalue
N.B.:
Similarly, min(x) returns the smallest element in the vector x and its position.
16
Ind = find(X) returns the indices of all nonzero elements of the vector X. Ind = find (logical expression on X) - evaluates the logical expression on the elements of the array X and returns the indices of those satisfying the logical expression. Example: a=[10,20,30,0,40,0,2,45] b=find(a) returns: b=1 b=find(a==10) returns: b=1 b=find(a>10) returns: b=2 b=find(a>10 & a<40) returns: b = 2
2 3
3 5
5 8
17
If: if expression sequence of statements elseif expression sequence of statements else sequence of statements end
18
For: for i = start range : increment : end range sequence of commands end
19
break : allows to exit early from the for or while loop in which it appears and to pass control to the first statement after the end of that loop.
N.B.: break is not defined outside a for or while loop
return: allows to stop the execution of the program completely, which causes an immediate return from the m.file.
20
Example1:
% get the sum S=1+2++100 n = 100; S=0; for i=1:n S=S+i; end S % or n=input('n= '); % Initialize S
21
Example2:
% get the smallest integer n such that S=1+2++n > 1000 n = 0; S = 0; while S<1000 n=n+1; S=S+n; end n,S % Initialize n % Initialize S
equivalently:
22
Files containing a code are m.files. m.files are created using a text editor File new m.file
Two kinds of m.files: Scripts: sequence of commands Functions: with input and output arguments m.files are used as any other MATLAB function or command
23
24
On the command window we run the function: [c d] = myaddProd(3,6) Matlab returns c =9 and d = 18 Note: For multiple output arguments include them between brackets and separate them by a comma For multiple input arguments include them between parentheses and separate them by a comma
25
function S = mySum(n)
Remark: tic and toc functions tic (operations) toc % measures the elapsed time
Experiment the tic-toc functions on the above example, when evaluating: mySum(100), mySum(106), mySum(1020),
26
Example 3:
function p = EvaluatePolyStraight(a,y)
% Input a vector a = [a(1),a(2),...,a(n+1)] % Input a real number y % Output the value of p(y) = a(n+1)*y^n + ... + a(2)*y + a(1)
Example 4:
function p = EvaluatePolyNested(a,y)
% Input a = [a(1),a(2),...,a(n+1)] and y % Output Value of p(y) = a(n+1)*y^n + ... + a(2)*y + a(1)
p( y) = 2 y + 3 y + y + 5 Let: Evaluate p(1) and p(1/3) in two ways, by calling the previous functions.
4 3
29
f = @(name of variables)(expression)
Examples:
Remarks: 1. When using the function handle, a function can be defined directly in the command window, without an m.file.
2.
Plotting two-dimensional Curves: plot (x,y, plotting options) generates a linear plot of the values of x (horizontal axis) and y (vertical axis).
Note:
The plotting options can be the color of the plot, its shape, the line width, its style
Plotting three-dimensional Curves: plot3 (x,y,z, plotting options) generates a linear plot of the values of (x,y,z) z is the vertical axis (default) Many tools are available: rotate 3D, Other: area graphs, surfaces, bar and scatter graphs, subplot (m, n, p) creates an m by n grid of windows, with p specifying the current plot as the p-th window.
31
title (text) -labels top of plot with text in quotes xlabel (text) -labels horizontal x-axis with text in quotes ylabel (text) -labels vertical y-axis with text in quotes text (x,y, text)-Adds text in quotes to location (x,y)on the current axes, where (x,y) is in units from the current plot. legend (string1, string2,) used to distinguish between plots on the same graph
hold on retain existing axes, add new curves to current axes. hold off release the current figure window for new plots
32
x = -pi:pi/10:pi; plot(x,sin(x)) For giving line specifications: plot(x,sin(x),'--r*','LineWidth',2) One can add: title('Sine function') xlabel('x') ylabel('sin x') grid on Or superpose: hold on plot(x,cos(x),'--b*','LineWidth',2)
33