You are on page 1of 9

..chapter 8 left in 1b.mtlb prgmng.. >> save filename.....saves all values in a workspace to be saevsd >> pcode function_name...saves fn in .

p format (compiled format)..will make main program run fast as it will save compiling each time >> date.....returns >> clock.... returns 6 element arraay [year maonth date hour minute seconds] >> >> error ('massage')......stops the program with prompting massage can be used w ith 'if' inside structure to stop program for some conditions to run extrnal programs >> !program name file name...OS goes to that program and only retuns when that program is closed startup.m: An optional M-file to be created by the user, typically containing co mmands that add personal default features. use desktop tool in start menu left bottm of matlab window to enter a matrix/number >> a=[1 2 3;1 3 4;1 3 4]....to write matrix ............................................................................... display >>fprintf ('stringstring %f string',valuename)...%f in the string is replaced by value >>disp (variablename)... or >>disp 'string' save load type pwd what save filename variable1 var2 var3... presenst in wworkspace or >> save filename ....saves all values

........................................................................... linear vectors >> a =startval:common diff:end point....as soon as series recheas endpt it stops >> a =linspace(startval,endpt,no of element)....equally separated elements are c reated >> a =logspace(start_exponent,end_exponent, no_of_element)...gives point on real scale >> sum (a) ......adds the columns..forms row matrix.to do it for row take transp ose eg. >>(sum (a'))' >> size (a)...returns size >> diag (a)...gives colum vector of dioganal elements >>a(1,2)....gives elements

if we call a no. out of dimension of matrix it shows error but if we put a no. t here it size of matrix change making a matrix out of other >>b= a (1:2, 2:3) >>b= a (:,4)...gives a column vector equal to 4th col.of matrix a abs, sqrt, exp, sin, matlab gives complex answer if some caluculatin like taking root of -ve is done i or j is root -1, pi, inf, NaN are used fir infinite and not a no. generating matrix >> zeros (,) >> eye(n)....identity matrix nXn >> ones (,) >> rand (,)....uniformly disrtbted nos >> randn (,)......nosrmally distributed nos

can read .m files or text files numeric data text file must have nos separated by spaces and equal element in rows...forms an matrix in matlab with that name >>load filename.extension

reduced row echolen >> rref(a) determinant >> det(a) inverse >> inv(a) eigenvalues >>eig (a) >> rank (a)...gives rank element by element(dimensin of matrix must match) + .* ./ .^

data is taken in col...mean(a) std(a) gives appropriare result...for help type > >help datafun or >>help stats ............................................ plots >>plot (x)...plots x vector wrt its position in vector array >>plot(x,y)...x,y are row matrix or scaler, >>subplot (m,n,p) >>hold......to hold plot and draw points in same plot without cleanig older data

to plot multiple data in one, >>grid >>plot (x,y1, x,y2 ,x,y3 )..and so on plot (x,y,'b*')....last argumnet has 2 parts first coloure and second line style rygbmc-red yellow green blue magenta cyan

>>semilogx(x,y)....plots graph using a log scale for x...similar >>semilogy (x,y ) and loglog(x,y) >>compass(z,'.') ..... polar plots >>xlabel('...'.)...... >>title ('...')... >>axis([x_start,x_end,y_start,y_end])....use both bracket >>text (x,y,'string') string will be written on plot at coordinate (x,y) >> >>print.....prints current graph to printer(in our case xps viewer or other prgm ) >> 3d plots >>mesh (a,b,c) ...or >>surf (a,b,c) ...where a,b and c are matrices of same dime nsion of which a and b can be created by >>[a,b]=meshgrid(A,B) where as c is a formula /matrix of array operators >>contour(x,y,z) >>contour(x,y,z,v).gives contour line plot..where x, y are range vector and not the grid. v gives contour values >>meshc (x,y,z)....gives a mesh plot and contour plot below it x,y can be both r ange vector or grid under the plot ............................................ multidimentional arrey a(2,3,5) is a 3-d array similarly a(,,,,) ........................................... scripts (.m files made in text editor and saved in matlab dir) piece of code which do not take or give output argument but it can operate on da ta in workspace can plot edit erase etc. simply write code no initiation no name giving just same the file as the name of operation u want..and then it can be used in main program as command dont keep name of any variabe same as any script or viceversa keep a difference ..,matlab gets confused.. >>which filename ...to see if file already exists with that name ............................................ functions (.m files made in text editor and saved in matlab dir) function output1,output2.. = function_name (argumnt1, argument 2, argumnt3...)

... ... output1=...;output2=...; can save as m files of same name as function and be called during work have their own variables doesnt interfear with main program...one cann although creat golbal variable inside a fn by >> global var_name it will shown in workspa ce and can be used/changed during program

using fn [a,b..] = functionname ('arg1','arg2'..) where a will gain value = outpt1 and likewise function have comments written in beginning which will appear when one gives com mand >> help functionname function handle @function_name....creates a handle to function we can also name it by initiating with >> tanay= @function name...or >>tanay= @(argument1, argument2..) arg1+arg2/43 ....... later tanay(1,2..) will return value =arg1+arg2/43.... handle can be used in arguments of other fuctions..eg suppose we create a functi on called "minimise" we cannot use x^2 as argument but @x^2 can be used ....................................... string >>sringname=['can write anything'] >>eval(string name) string name eqals any variable or fn or programm it will be executed ......................................... tipsalready create the variable which are being formed in some loop avoid for while if can use vactorization ie solve in matrix form example x = .01; for k = 1:1001 y(k) = log10(x); x = x + .01; end A vectorized version of the same code is Scripts and Functions 5-23 x = .01:.01:10;

y = log10(x); ........................................................... mathematics norm(a)...gives magnitude of vector; >> dot(a,b)...dot product of vector >> cross(a,b)...a,b must be 3d vectors sin (a), cos(a), tan (a), asin(b), acos(b), atan(b),sinh(x),asinh(x) etc.. sind (a)....gives value of sin for a in degree...add d for using in degree complex no..not differnet...z=2+i*2 or >> z=5*exp(i*angle) abs(z) Complex magnitude z or absolute value angle(z) Phase angle or argument of z conj(z) Complex conjugate z* imag(z) Complex imaginary part real(z) Complex real part plot(z, . ) integration: >> trapz(x,y)....returns a single scaler value >> cumtrapz(x,y)...returns a vector equal to x and y giving integration upto poi nt at each location first pt=0 last pt = total integral..important while ploting >> quad('function', a,b)....a and b are limits function is a string functions ca n be made in .m file >> quad8 ('function',a,b)....better than previous >> dblquad ('function',xmin,xmax,ymin,ymax)..as clear by name it integrates for double variable fuction must be defined before differentiation >> diff (a)...returns a vector of differences of adjescent element;length one le ss than that of a >> gradient(y,h) returns the finite difference approximation of dy/dx at each po int, where h is the spacing between the points. >> d2 = del2(y,h) returns the finite difference approximation of d2y/dx2 /4 at e ach point, where h is the spacing between the points

................................................................. strigs take this example >> text = This is a character string ; >> u = text(11:19) u= character

..................................................................... polynomial can use coef matrix for operations addition/subtraction/multor division by scaler is done by performingsame oprn on coefvectors >> polyval(coef_matrix, xvalues)...returns vector containng values of pol for x >> conv (coef_a, coef_b)...returns pol coefvector of A*b >> [q,r] = deconv(coef_a, coef_b)...returns coef_vector of quotient and remainde r >> polyder(a)...returns coef of derivative

>> roots(a)....returns root of polynomial(recall that the complex no are used as single variable and stored in one element ofa array or matrix) >> poly(r).... Returns coef vector for polynomial whose roots are represented by r remember a polynom. can be factorised as (x-r1)*(x-r2)*... where r1,r2 are roots found by roots(a) command

>> [c,r] =residue(a,b)....gives partial fractions >>[c,r,q]= residue (a,b)....gives partial fraction and quotient in case of impro per rational expression (in case of repeted roots matlab assumes the power has been raised, complex root s are shown complex) pol= pol(a)/pol(b)>>>>--partial fn---->c1/(x-rootofb1) + c2/(x-rootofb2) in case

so c gives c1,c2,... and r gives corresponding root. in case of improper rationa l expr^n q gives quotient polynomial.

>> x = fzero(@func,x0) returns the zero of the function func closest to x0. >> x = fzero(@func,[a b]) can be usedwhen the root has beenbracketed in(a,b).

..................................................................... data analysis...>> help datafun

>> max (x)...returns row vector containing largest value of column, also works f or single row vector >> [x,y]= max(a)....returns vector x containing max of each column and y conatai ning ther respective row histogram is same as frequenyc chart..freq of occurnce is shown in y xis and on x-axis the range of data (centered around one pt or bounded by given edge pt) >>hist(a)....returns a row matrix histogram based on automatically selected valu e of data in 10 bins if a is matrix it operates on each col ..returns histograms for each column >>hist(a,m)...same but no of column in hist equal to m if m is scaler >>hist(a,b)...gives histograms for bin value given in b vector >>[n,xc]= hist (a)....n is hitogram & xc are bin-centers..(not edges) >> histc(a,edges)...returns histogram for edges given(edges vector must be stric tly non decreasingsame value for 2 time is fine)....edge(i)>= X > edge(i+1) >>mean meadian std....returns appropriate values, if argument is matrix opratio n is perforned on each col..row vectoer returned >>sort(a)..sorts in ascending order..same as above ........................................................................... programming <=...less than or equal, ~ = not equal, & and, or, ~ not, xor(a,b) == equal

>> any(x).... Returns 1 (true) if any element in x is nonzero; otherwise, 0 >> all(x).... Returns 1 (true) if all elements in x are nonzero; otherwise,0 >> isnan(x)... Returns an array with '1' where the elements of x are NaN and '0' where they are not. >> isfinite(x) Returns an array with '1' where the elements of x are ?nite >> isinf(x) .........similar,note that infinte is not fully written >>isempty(x).... Returns 1 if x is an empty array and 0 otherwise. >>input('any prompt')..... untill enter is typed >>[x,y,b]= ginput(n)...returns coordinates of cursor for n points if enter is pr esses before n points are entered intake stops,b gives which button was pressed 1,2,3 for left middle and right click... >>keyboard....gives conttrol to keyboard untill return is typed >>pause(n)......pause for n second...or >>pause....pause untill any key pressed >>rand.......(wtout any argument) gives rand no each time its reffered == compares 2 matrices and returns a matrix of 1and 0.. 0 for being equal...show s error if matrix size differ safe in case of scalers > ...compare if greater, returns boolean matrix (same as ==) isequal(a,b)....gives 1 or 0 in case of matrices safe to use in if statements

similarly isempty(a), ................................................................................ .. if a>b .......... else if logicalexprn ........ else ....... end ............................. loops (for, while) for i=a:b .... end while logical cond. ...... end on infinite loop constrained by logical conditi

example: while a>b ... end loops can be broken by ..>>break only innermost loop is broken (for or while),at the same time in a loop by using >>continue that iteration can be left saving w hole program to run.

............................................................................... curve fittinng >> polyfit(xpts,ypts,n)....returns coef vector for n degree best fit polynomial, for n=1 gives best fit line

>> interpl(x,y,xpts)...return ypts wrt xpts based on linear interpolation of (x, y) points,..values in x must be ascending >> ypts=spline (x,y,xpts)...returns y value wrt xpts based on spline interpolati on >> ypts= spline (x,[a, y, b], ypts),....the second argumnt is an arrey of pts wi th first and last element equal to its slope at the endpoints...otherwise its ta ken as 0..in previous command ................................................................................ ..

techneques solution to multiple nonlinear eqn f1(x1, x2...,xn)=0, f2(x1, x2...,xn)=0......n eqn n variable df1/dx1 df1/dx2 ...df1x/dxn df2/dx1 df2/dx2 ...df2/dxn . . . dfn/dx1 dfn/dx2 ...dfn/dxn dx1 dx2 . . . dxn f1 f2 = . . . fn

oteration r done by adding dxi values to previous values .............................................................. optimisation powells method in n dimention start at a point minimise in the line passing through that pt , establish this p t as starting pt and re-do previous step in 2nd direction...repeat untill distan ce btwn old and new pt is very small >> x = fminbnd(@func, a,b)....returns x that minimises function 'func'of single variable. a,b are domain >> x = fminsearch(@func, xstart).. return vector of n indipendent variable where func is minimum, xstart is staring point (n dimention) ........................................ ................................................................

You might also like