Beruflich Dokumente
Kultur Dokumente
It stands for MATrix LABoratory. It is used as an Object-oriented high-level interactive software package for scientific and engineering numerical computations. Enables easy manipulation of matrix and other computations. Can handle symbolic computation but is not specifically tailored to do that. The variable name must begin with a letter of alphabet e.g variablename = expression, e.g., mynum=3, mynum=4+2, mynum=mynum+1, mynum=mynum+3, mynum. MATLAB is case sensitive. e.g., num, NUM, Num are different variables. Although, under-score _ is allowed. But try to avoid. Use partWeight instead of part_weight. The reserved words or key words or name of built-in functions are NOT to be used. Variable names should make sense.
type who in command window then press enter, who Your variables are:
ans o Whos
it also lists all current variables (long display) in use during a session e.g
Clear
It removes all function or variable name from the workspace. freeing up system memory. Just type clear in command window and press enter.
clear variablename It removes a specific function or variable name from the workspace as we want.e.g according to the syntax type clear g where g is the variable to be removed from workspace. clear variablename1 varaiablename2 It is used if you want to remove more than one functions or variable names from the workspace e.g according to the syntax type clear c p where c and p are the variables to be removed from workspace. format long
Control display format for output. It is a scaled fixed point format, with 15 digits for double; 8 digits for single.e.g Change the format to long by typing format long View the result for the value of pi by typing pi ans = 3.14159265358979
Scaled fixed point format, with 5 digits e.gChange the format to short by typing format short format short pi ans = 3.1416
OPERATORS They are the basic operators as used in linear algebra + Addition - Subtraction * Multiplication / Division or Right division (divided by) \ Left division or Back slash (divided into) ^ exponentiation. PRECEDNCE RULES They decide which part of a mathematical expression must be solved first in MATLAB while performing that mathematical calculation ( ) parenthesis ^ exponentiation *, /, \ all multiplication and division +, - addition and subtraction.
For a complex no.(3+4i)the functions used are abs(x) Absolute value; |x|.syntax with result abs(3+4i) ans = 5
angle(x) Angle of a complex number x. angle(3+4i)
ans = 0.92729521800161 conj(x) Complex conjugate of x. conj(3+4i) ans = 3.00000000000000 - 4.00000000000000i imag(x) Imaginary part of a complex number x. imag(3+4i) ans = 4
real(x) Real part of a complex number x. real(3+4i)
ans = 3
ans = 20.08553692318767 log(x) Default values of log(x)are actually values of Natural logarithm ln(x) log(-1) ans = 0 + 3.14159265358979i log10(x) Common (base 10) logarithm; log(x)= log10(x)e.g
ARRAYS, VECTORS AND MATRICES a=[1 2 3 4]------------A row vector or an array having four elements. a =1 2 3 4 b=[1;2;3;4]------------A column vector or an array having four elements. b =1 2 3 4 c=[1,2; 3,4]-----------A 2 x 2 matrix or 2 x 2 array. c =1 2 3 4 t=[1:5]--------------: operator, used to create an array from 1 to 5 with an increment of 1. t=1 2 3 4 5 t1=[1:2:5]------------an array from 1 to 5 with an increment of 2. t =1 3 5 t2=[5:-1:1]-----------an array from 5 to 1 with a decrement of 1 t=5 4 3 2 1
LINSPACE COMMAND linspace(x1, x2) generates a row vector of 100 linearly equally spaced points between x1 and x2.e.g linspace(1,2) ans = Columns 1 through 10 1.0000 1.0101 1.0909 1.0202 1.0303 1.0404 1.0505 1.0606 1.0707 1.0808
Columns 11 through 20
1.1212
1.1313
1.1414
1.1515
1.1616
1.1717
1.1818
Columns 21 through 30 1.2020 1.2121 1.2929 1.2222 1.2323 1.2424 1.2525 1.2626 1.2727 1.2828
Columns 31 through 40 1.3030 1.3131 1.3939 1.3232 1.3333 1.3434 1.3535 1.3636 1.3737 1.3838
Columns 41 through 50 1.4040 1.4141 1.4949 1.4242 1.4343 1.4444 1.4545 1.4646 1.4747 1.4848
Columns 51 through 60 1.5051 1.5152 1.5960 1.5253 1.5354 1.5455 1.5556 1.5657 1.5758 1.5859
Columns 61 through 70 1.6061 1.6162 1.6970 1.6263 1.6364 1.6465 1.6566 1.6667 1.6768 1.6869
Columns 71 through 80 1.7071 1.7172 1.7980 1.7273 1.7374 1.7475 1.7576 1.7677 1.7778 1.7879
Columns 81 through 90 1.8081 1.8182 1.8990 1.8283 1.8384 1.8485 1.8586 1.8687 1.8788 1.8889
1.9091 1.9192 1.9293 1.9394 1.9495 1.9596 1.9697 1.9798 1.9899 2.0000 linspace(x1, x2, n) generates n points between x1 and x2. For n < 2, linspace returns x2.e.g linspace(1,10,6) ans = 1.0000 2.8000 4.6000 6.4000 8.2000 10.0000 LOGSPACE COMMAND logspace(x1, x2) generates a row vector of 50 logarithmically equally spaced points between decades 10^x1 and 10^x2. logspace(1,2) ans = Columns 1 through 10 10.0000 10.4811 10.9854 14.5635 15.2642 Columns 11 through 20 15.9986 16.7683 17.5751 23.2995 24.4205 Columns 21 through 30 25.5955 26.8270 28.1177 37.2759 39.0694 Columns 31 through 40 40.9492 42.9193 44.9843 59.6362 62.5055 Columns 41 through 50 65.5129 68.6649 71.9686 95.4095 100.0000 75.4312 79.0604 82.8643 86.8511 91.0298 47.1487 49.4171 51.7947 54.2868 56.8987 29.4705 30.8884 32.3746 33.9322 35.5648 18.4207 19.3070 20.2359 21.2095 22.2300 11.5140 12.0679 12.6486 13.2571 13.8950
logspace(x1, x2, n) generates n points. For n < 2, logspace returns 10^x2. E.g logspace(1,2,5) ans = 10.0000 17.7828 31.6228 56.2341 100.0000 Useful commands/functions related to vectors, are given below: For a vector q=[4 2 7 -1], 1. sum( ) this command gives the sum of all the elements in a row/column vector. sum(q) ans = 12 2. mean( ) It gives average of the elements of a row/column vector. mean(q) ans = 3 3. length( ) It gives the number of elements in a row/column vector. length(q) ans = 4 4. max( ) It gives the maximum value in the row/column vector. max(q) ans = 7 5. min( ) It gives the minimum value in the row/column vector. min(q) ans = -1 6. prod( ) It gives the product of elements of row/column vector. prod(q)
ans = -56 7. sign( ) It returns 1, if the sign of an element of a vector is +ve, return 0, if element is 0, and return 1 if sign is ve. sign(q) ans = 1 1 1 -1 8. fix( ) It rounds the elements of a vector to the nearest integers towards zero. fix(q) ans = 4 2 7 -1 9. floor( ) It rounds the elements of a vector to the nearest integer towards . 10. ceil( )It rounds the elements of a vector to the nearest integer towards +. 11. round( ) It rounds the elements of a vector to the nearest integers. 12. sort( ) It lists the elements of a vector in the ascending order. sort(q) ans = -1 2 4 7 We can also have a descending order by the command sort(vectorName, descend). sort(q,'descend') ans = 7 4 2 -1 MATRICES Input the following matrices: A=[1 2 3; 4 5 6;7 8 9] A= 1 4 7 2 5 8 3 6 9
SUB-MARTICES Let a matrix A be defined as A=[1 2 3; 4 5 6;7 8 9]. The command A(1:2, 2:3) gives only elements of rows 1 & 2 in the column 2 & 3. ans = 2 3 5 6 The command A(:, 2:3) gives all rows in columns 2 & 3, i.e., the : when typed alone, refers to all elements in a row or column of a matrix. ans = 2 3 5 6 8 9 Similarly, the command A(1:2, 3) gives elements of rows 1 & 2 in the 3rd column. ans = 3 6 GENERATION OF SPECIAL MATRICES zeros(p,q) Returns a matrix of all zeros of order pxq. zeros(2,3) ans = 0 0 0 0 0 0 ones(p,q) Returns a matrix of all ones of order pxq. ones(2,3) ans = 1 1 1 1 1 1 eye(p,q) Returns a matrix with ones on the main diagonal and zeros elsewhere of order pxq. eye(2,3)
ans = 1 0 0 0 1 0 rand(n) Generates a matrix of order nxn with random entries, chosen from a uniform distribution on the interval (0, 1). rand(2) ans = 0.9501 0.6068 0.2311 0.4860 rand(m, n) Generates a matrix of order mxn with random entries, chosen from a uniform distribution on the interval (0, 1). rand(2,3) ans = 0.8913 0.4565 0.8214 0.7621 0.0185 0.4447 rands(n) Generates a matrix of order nxn with random entries, chosen from a uniform distribution on the interval (-1, +1). rands(2) ans = 0.2309 0.8436 0.5839 0.4764 rands(m, n) Generates a matrix of order mxn with random entries, chosen from a uniform distribution on the interval (-1, +1). rands(2,3) ans = -0.6475 0.8709 -0.1795 -0.1886 0.8338 0.7873 diag(v) If v is a row or column vector with n elements, it returns a diagonal
matrix, with v as its diagonal. v=[2 3 4 5] diag(v) ans = 2 0 0 0 0 3 0 0 0 0 4 0 0 0 0 5 SOME USFUL COMMANDS RELATED TO MATRICES For A=[1 3; 4 6], det( ) Returns the determinant of a given square matrix. det(A) ans = -6 rank( ) Returns the rank of a given square matrix. rank(A) ans = 2 trace( ) Returns the sum of the diagonal elements of a square matrix. trace(A) ans = 7 inv( ) Returns the inverse of a non-singular square matrix. inv(A) ans = -1.0000 0.5000 0.6667 -0.1667 x=A\b It returns the solution vector x of a linear system described by a set of linear algebraic equations Ax=b. i.e., x=A b. poly( ) It returns the coefficients of the characteristic polynomial p of the
-1
matrix A, i.e., the coefficients of the determinant of the matrix [], where, I is the identity matrix. eig( ) Returns the eigen values of a matrix A. eig(A) ans = -0.7720 7.7720 [v ,x]=eig(A) It returns the eigen vector v, and eigen values shown on the main diagonal of the matrix x [v ,x]=eig(A) v= -0.8610 -0.4050 0.5086 -0.9143 x= -0.7720 0 0 7.7720 ARITHMATIC OPERATIONS ON MATRICES Matrix operations follow the rules of linear algebra in MATLAB. It allows the following arithmetic operations to be carried out on matrices provided that the operands are compatible with the operations. + Addition Subtraction * Multiplication / Right division ^ Exponentiation \ Left division
So far we have typed and executed all command directly from the command window but the problem is that the commands entered in the Command Window cannot be saved and executed again for several times. Therefore, a different way of executing repeatedly commands with MATLAB is: 1. to create a file with a list of commands, 2. save the file, and 3. run the file. If needed, corrections or changes can be made to the commands in the file. The files that are used for this purpose are called script files or scripts for short. This section covers the following topics: M-File Scripts M-File Functions
M-File Scripts
A script file is an external file that contains a sequence of MATLAB statements. Script files have a filename extension .m and are often called M-files. M-files can be scripts that simply execute a series of MATLAB statements, or they can be functions that can accept arguments and can produce one or more outputs.
Examples
Here is a simple script.
Example 1
Consider the system of equations: x + 2y + 3z = 1 3x + 3y + 4z = 1 2x + 3y + 3z = 2 Find the solution x to the system of equations.
Solution: Use the MATLAB editor to create a file: File New M-file.
Enter the following statements in the file:
M-File functions
As mentioned earlier, functions are programs (or routines) that accept input arguments and return output arguments. Each M-file function (or function or M-file for short) has its own area of workspace, separated from the MATLAB base workspace.
function f = factorial(n) %(1) % FACTORIAL(N) returns the factorial of N. %(2) % Compute a factorial value. %(3) f = prod(1:n); %(4)
The first line of a function M-file starts with the keyword function. It gives the function name and order of arguments. In the case of function factorial, there are up to one output argument and one input argument. As an example, for n = 5, the result is,
>> f = factorial(5)
f= 120 The following Table summarizes the M-file function. Eq No (1) M-file element Description
(2)
H1 line
(3) (4)
Define the function name, and the number and order of input and output arguments A one line summary description of the program, displayed when you request Help A more detailed description of the program Program code that performs the actual computations.
There is also a very important command of Plot through which we can plot a graph of any function as we please.Lets see an example:
Plot the following cosine functions, y1 = 2 cos(x), y2 = cos(x), and y3 = 0:5 cos(x), in the interval 0 x 2. We put the commands in a file. Create a file, say example2.m, which contains the following commands:
x = 0:pi/100:2*pi; y1 = 2*cos(x); y2 = cos(x); y3 = 0.5*cos(x); plot(x,y1,'--',x,y2,'-',x,y3,':') xlabel('0 \leq x \leq 2\pi') ylabel('Cosine functions')
String Functions
findstr Finds occurrences of a string.
s1=ali
s2=ali strcmp(s1,s2)
ans =
1
Strmatch Matches a string
s1=ali >>s2=ali >> strmatch(s1,s2) There are two methods of display any character string
Fprintf Write formatted data to file the syntax is count = fprintf(fid,format,A,...) The command fprintf('A unit circle has circumference %g radians.\n',2*pi) displays a line on the screen: A unit circle has circumference 6.283186 radians. To insert a single quotation mark in a string, use two single quotation marks together. For example, fprintf(1,'It''s Friday.\n') displays on the screen It's Friday. The commands B = [8.8 7.7; 8800 7700] fprintf(1,'X is %6.2f meters or %8.3f mm\n',9.9,9900,B) display the lines X is 9.90 meters or 9900.000 mm X is 8.80 meters or 8800.000 mm X is 7.70 meters or 7700.000 mm sprint Write formatted data to the string with syntax
[s, errmsg] = sprintf(format, A, ...) ExamplesCommandResultsprintf('%0.5g',(1+sqrt(5))/2)1.618sprintf('%0.5g',1/eps)4.5036e+15sprintf('%15.5f',1 /eps) 4503599627370496.00000sprintf('%d',round(pi))3sprintf('%s','hello')hellosprintf('The array is %dx%d.',2,3)The array is 2x3sprintf('\n')Line termination character on all platforms
Interpolation Methods in MATLAB 1: Nearest neighbor: It is fastest method.it provides worst results in terms of smoothness 2: linear (by default) This method uses more memory than nearest neighbor method, but its results are continuous as compared to nearest method. 3:cubic spline It has longest execution time and requires less memory, its results are smoothest of all the methods. 4:Cubic interpolation it requires more memory and execution time than either the nearest and linear interpolation methods. however the data and its derivatives are continuous.
There is an example %%%%%%first v give values of t and v%%%%% t=[0 20 40 56 68 80 84 96 104 110] v=[0 20 20 38 80 80 100 100 125 125] w=linspace(1,110,100) %%%%%%%%interpolation with nearest neighbour method and plot%%%%%%%%%%% x=interp1(t,v,w,'nearest') subplot(2,2,1),plot(t,v,'*',w,x) xlabel('Time(t)') ylabel('Velocity(v)') %%%%%%%%%%%title%%%%% title('interpolation using nearest neighbour method') %%%%%%%%interpolation with spline methd and plot%%%%%%%%% x=interp1(t,v,w,'spline') subplot(2,2,2),plot(t,v,'*',w,x) %%%%%%%%%%%title%%%%% title('interpolation using spline method') xlabel('Time(t)') ylabel('Velocity(v)') %%%%%%%%interpolation with cubic method and plot%%%%%%%%%%% x=interp1(t,v,w,'cubic')
% clears the Screen % declaring x as an independent variable %enter coeffiecients of function % takes derivative of function % enter your initial guess for root %initialize variable i to carry out iterations %initializes for loop % calculates function value at xo % calculates value of derivative of function at xo % Newton Raphson formula % calculates approximate error % increments number of iterations %assigns value of xnew to xo % terminates for loop
disp('root does not lie in given interval') else disp(root lies in given interval) end for i=1:10 xr=(xu+xl)/2 c=polyval(func,xl) d=polyval(func,xr) check=c*d message if(check>0) disp('root lies in upper subinterval') xl=xr %initializes for loop for 10 itarations % calculate mid point of interval % evaluate function at xl %evaluate function at xr
end
if(check<0) disp('root lies in lower subinterval') xu=xr end i=i+1 end k=-5:1:5
y=polyval(func,k) plot(k,y)
Examples: Solve the following differential equation using MATLABs dsolve command: + Assuming initial condition y(0)=1 >>y=dsolve('Dy+4*y = exp(-t)', 'y(0) = 1')
>>dsolve(Dy=-2*y,y(0)=3) + +
>>dsolve(D2y+4Dy+4y=0, y(0)=1,Dy(0)=0)
MATLAB backslash
The Matlab backslash operator solve linear systems of equations. If you desire the solution of Ax = b, then the simplest method using Matlab to find x is to set x = A\b. If A is an n by m matrix and b is an p by q matrix then A\b is defined (and is calculated by Matlab) if m=p.. >>A = [ 1 2; 3 4] >>b = [1 0] >>X=inv(A)*b Or >>X=A\b
example, y = x.^2 is a parabola that touches the x-axis at 0. Because the function never crosses the x-axis, however, no zero is found. For functions with no valid zeros, fzero executes until Inf, NaN, or a complex value is detected.
fun x
A string containing the name of a file in which an arbitrary function of one variable is defined. Your initial estimate of the x-coordinate of a zero of the function or an interval in which you think a zero is found.
Examples
Calculate by finding the zero of the sine function near 3. >>x = fzero('sin',3) x = 3.1416 To find the zero of cosine between 1 and 2
>>x = fzero('cos',[1 2]) x = 1.5708
Note that cos(1) and cos(2) differ in sign.
It returns NaN since this function does not change sign anywhere on the real axis (and does not have a zero as well).
Limitations
The fzero command defines a zero as a point where the function crosses the x-axis. Points where the function touches, but does not cross, the x-axis are not valid zeros. For example, y = x.^2 is a parabola that touches the x-axis at (0,0). Since the function never crosses the x-axis, however, no zero is found. For functions with no valid zeros, fzero executes until Inf, NaN, or a complex value is detected
MATLAB Constants
Names of built in MATLAB constants include:
ans: the result of the most recent calculation; computer: the computer type; eps: the machine epsilon; flops: the number of floating point operations; i, j: square root of -1; inf: "infinity", the result of 1/0, for instance; NaN: "Not a Number", the result of 0/0, for instance; pi realmax, realmin: largest and smallest representable reals; version: MATLAB version number.
Machine epsilon
Machine epsilon also known as eps in MATLAB is the distance from 1 to the next valid floating point number..This value is used in determining the numerical rank of the matrix and in determining the pseudo inverse of a matrix. On an intel based machine Eps=2-52=2.22*10-16
VECTORIZATION
Vectorization means converting for and while loops to equivalent vector or matrix operations
MATLAB is designed to perform vector and matrix operations efficiently.The concept of vectorization is central to understanding how to write efficient MATLAB code. MATLAB is designed to perform vector and matrix operations efficiently. To take maximum advantage of the computer hardware at your disposal, therefore, you should use vectorized operations as much as possible The MATLAB software uses a matrix language, which means it is designed for vector and matrix operations. You can often speed up your code by using vectorizing algorithms that take advantage of this design.