Matlab - Getting start, страница 12

PDF-файл Matlab - Getting start, страница 12 Цифровая обработка сигналов (ЦОС) (15294): Книга - 8 семестрMatlab - Getting start: Цифровая обработка сигналов (ЦОС) - PDF, страница 12 (15294) - СтудИзба2017-12-27СтудИзба

Описание файла

PDF-файл из архива "Matlab - Getting start", который расположен в категории "". Всё это находится в предмете "цифровая обработка сигналов (цос)" из 8 семестр, которые можно найти в файловом архиве МГТУ им. Н.Э.Баумана. Не смотря на прямую связь этого архива с МГТУ им. Н.Э.Баумана, его также можно найти и в других разделах. Архив можно найти в разделе "книги и методические указания", в предмете "цифровая обработка сигналов" в общих файлах.

Просмотр PDF-файла онлайн

Текст 12 страницы из PDF

The M-file rank.m is available in thedirectorytoolbox/matlab/matfun5-18Scripts and FunctionsYou can see the file withtype rankHere is the file.function r = rank(A,tol)%RANK Matrix rank.%RANK(A) provides an estimate of the number of linearly%independent rows or columns of a matrix A.%RANK(A,tol) is the number of singular values of A%that are larger than tol.%RANK(A) uses the default tol = max(size(A)) * norm(A) * eps.s = svd(A);if nargin==1tol = max(size(A)') * max(s) * eps;endr = sum(s > tol);The first line of a function M-file starts with the keyword function. It gives thefunction name and order of arguments. In this case, there are up to two inputarguments and one output argument.The next several lines, up to the first blank or executable line, are commentlines that provide the help text.

These lines are printed when you typehelp rankThe first line of the help text is the H1 line, which MATLAB displays when youuse the lookfor command or request help on a directory.The rest of the file is the executable MATLAB code defining the function. Thevariable s introduced in the body of the function, as well as the variables on thefirst line, r, A and tol, are all local to the function; they are separate from anyvariables in the MATLAB workspace.This example illustrates one aspect of MATLAB functions that is not ordinarilyfound in other programming languages – a variable number of arguments.

Therank function can be used in several different ways.rank(A)r = rank(A)r = rank(A,1.e-6)5-195Programming with MATLABMany M-files work this way. If no output argument is supplied, the result isstored in ans. If the second input argument is not supplied, the functioncomputes a default value. Within the body of the function, two quantitiesnamed nargin and nargout are available which tell you the number of inputand output arguments involved in each particular use of the function.

The rankfunction uses nargin, but does not need to use nargout.Global VariablesIf you want more than one function to share a single copy of a variable, simplydeclare the variable as global in all the functions. Do the same thing at thecommand line if you want the base workspace to access the variable. The globaldeclaration must occur before the variable is actually used in a function.Although it is not required, using capital letters for the names of globalvariables helps distinguish them from other variables. For example, create anM-file called falling.m.function h = falling(t)global GRAVITYh = 1/2*GRAVITY*t.^2;Then interactively enter the statementsglobal GRAVITYGRAVITY = 32;y = falling((0:.1:5)');The two global statements make the value assigned to GRAVITY at thecommand prompt available inside the function.

You can then modify GRAVITYinteractively and obtain new solutions without editing any files.Passing String Arguments to FunctionsYou can write MATLAB functions that accept string arguments without theparentheses and quotes. That is, MATLAB interpretsfoo a b casfoo('a','b','c')5-20Scripts and FunctionsHowever, when using the unquoted form, MATLAB cannot return outputarguments. For example,legend apples orangescreates a legend on a plot using the strings apples and oranges as labels.

If youwant the legend command to return its output arguments, then you must usethe quoted form.[legh,objh] = legend('apples','oranges');In addition, you cannot use the unquoted form if any of the arguments are notstrings.Constructing String Arguments in CodeThe quoted form enables you to construct string arguments within the code.The following example processes multiple data files, August1.dat,August2.dat, and so on. It uses the function int2str, which converts aninteger to a character, to build the filename.for d = 1:31s = ['August' int2str(d) '.dat'];load(s)% Code to process the contents of the d-th fileendA Cautionary NoteWhile the unquoted syntax is convenient, it can be used incorrectly withoutcausing MATLAB to generate an error. For example, given a matrix A,A =06-5-6220-1-16-10The eig command returns the eigenvalues of A.eig(A)ans =-3.0710-2.4645+17.6008i-2.4645-17.6008i5-215Programming with MATLABThe following statement is not allowed because A is not a string, howeverMATLAB does not generate an error.eig Aans =65MATLAB actually takes the eigenvalues of ASCII numeric equivalent of theletter A (which is the number 65).The eval FunctionThe eval function works with text variables to implement a powerful textmacro facility.

The expression or statementeval(s)uses the MATLAB interpreter to evaluate the expression or execute thestatement contained in the text string s.The example of the previous section could also be done with the following code,although this would be somewhat less efficient because it involves the fullinterpreter, not just a function call.for d = 1:31s = ['load August' int2str(d) '.dat'];eval(s)% Process the contents of the d-th fileendVectorizationTo obtain the most speed out of MATLAB, it’s important to vectorize thealgorithms in your M-files. Where other programming languages might use foror DO loops, MATLAB can use vector or matrix operations. A simple exampleinvolves creating a table of logarithms.x = .01;for k = 1:1001y(k) = log10(x);x = x + .01;endA vectorized version of the same code is5-22Scripts and Functionsx = .01:.01:10;y = log10(x);For more complicated code, vectorization options are not always so obvious.When speed is important, however, you should always look for ways tovectorize your algorithms.PreallocationIf you can’t vectorize a piece of code, you can make your for loops go faster bypreallocating any vectors or arrays in which output results are stored.

Forexample, this code uses the function zeros to preallocate the vector created inthe for loop. This makes the for loop execute significantly faster.r = zeros(32,1);for n = 1:32r(n) = rank(magic(n));endWithout the preallocation in the previous example, the MATLAB interpreterenlarges the r vector by one element each time through the loop. Vectorpreallocation eliminates this step and results in faster execution.Function HandlesYou can create a handle to any MATLAB function and then use that handle asa means of referencing the function.

A function handle is typically passed in anargument list to other functions, which can then execute, or evaluate, thefunction using the handle.Construct a function handle in MATLAB using the at sign, @, before thefunction name. The following example creates a function handle for the sinfunction and assigns it to the variable fhandle.fhandle = @sin;Evaluate a function handle using the MATLAB feval function. The functionplot_fhandle, shown below, receives a function handle and data, and thenperforms an evaluation of the function handle on that data using feval.function x = plot_fhandle(fhandle, data)plot(data, feval(fhandle, data))5-235Programming with MATLABWhen you call plot_fhandle with a handle to the sin function and theargument shown below, the resulting evaluation produces a sine wave plot.plot_fhandle(@sin, -pi:0.01:pi)Function FunctionsA class of functions, called “function functions,” works with nonlinear functionsof a scalar variable.

That is, one function works on another function. Thefunction functions include:• Zero finding• Optimization• Quadrature• Ordinary differential equationsMATLAB represents the nonlinear function by a function M-file. For example,here is a simplified version of the function humps from the matlab/demosdirectory.function y = humps(x)y = 1./((x-.3).^2 + .01) + 1./((x-.9).^2 + .04) - 6;Evaluate this function at a set of points in the interval 0 ≤ x ≤ 1 withx = 0:.002:1;y = humps(x);Then plot the function withplot(x,y)5-24Scripts and Functions100908070605040302010000.10.20.30.40.50.60.70.80.91The graph shows that the function has a local minimum near x = 0.6.

Thefunction fminsearch finds the minimizer, the value of x where the functiontakes on this minimum. The first argument to fminsearch is a function handleto the function being minimized and the second argument is a rough guess atthe location of the minimum.p = fminsearch(@humps,.5)p =0.6370To evaluate the function at the minimizer,humps(p)ans =11.2528Numerical analysts use the terms quadrature and integration to distinguishbetween numerical approximation of definite integrals and numerical5-255Programming with MATLABintegration of ordinary differential equations.

MATLAB’s quadrature routinesare quad and quadl. The statementQ = quadl(@humps,0,1)computes the area under the curve in the graph and producesQ =29.8583Finally, the graph shows that the function is never zero on this interval. So, ifyou search for a zero withz = fzero(@humps,.5)you will find one outside of the intervalz =-0.13165-26Demonstration Programs Included with MATLABDemonstration Programs Included with MATLABMATLAB includes many demonstration programs that highlight variousfeatures and functions. For a complete list of the demos, at the commandprompt typehelp demosTo view a specific file, for example, airfoil, typeedit airfoilTo run a demonstration, type the filename at the command prompt. Forexample, to run the airfoil demonstration, typeairfoilNote Many of the demonstrations use multiple windows and require you topress a key in the MATLAB Command Window to continue through thedemonstration.The following tables list some of the current demonstration programs that areavailable, organized into these categories:• Matrix demos• Numeric demos• Visualization demos• Language demos• ODE suite demos• Gallery demos• Game demos• Miscellaneous demos• Helper function demos5-275Programming with MATLAB.MATLAB Matrix Demonstration ProgramsairfoilGraphical demonstration of sparse matrix from NASAairfoil.buckydemConnectivity graph of the Buckminster Fuller geodesicdome.delsqdemoFinite difference Laplacian on various domains.eigmovieSymmetric eigenvalue movie.eigshowGraphical demonstration of matrix eigenvalues.introIntroduction to basic matrix operations in MATLAB.inverterDemonstration of the inversion of a large matrix.matmanipIntroduction to matrix manipulation.rrefmovieComputation of reduced row echelon form.sepdemoSeparators for a finite element mesh.sparsityDemonstration of the effect of sparsity orderings.svdshowGraphical demonstration of matrix singular values.MATLAB Numeric Demonstration Programs5-28benchMATLAB benchmark.censusPrediction of the U.S.

population in the year 2000.e2piTwo-dimensional, visual solution to the problemπe“Which is greater, e or π ?”fftdemoUse of the FFT function for spectral analysis.fitdemoNonlinear curve fit with simplex algorithm.fplotdemoDemonstration of plotting a function.Demonstration Programs Included with MATLABMATLAB Numeric Demonstration Programs (Continued)funfunsDemonstration of functions operating on otherfunctions.lotkademoExample of ordinary differential equation solution.quaddemoAdaptive quadrature.quakeLoma Prieta earthquake.spline2dDemonstration of ginput and spline in twodimensions.sunspotsDemonstration of the fast Fourier transform (FFT)function in MATLAB used to analyze the variations insunspot activity.zerodemoZero finding with fzero.MATLAB Visualization Demonstration ProgramscolormenuDemonstration of adding a colormap to the currentfigure.cplxdemoMaps of functions of a complex variable.earthmapGraphical demonstrations of earth’s topography.graf2dTwo-dimensional XY plots in MATLAB.graf2d2Three-dimensional XYZ plots in MATLAB.grafcplxDemonstration of complex function plots in MATLAB.imagedemoDemonstration of MATLAB’s image capability.imageextDemonstration of changing and rotating imagecolormaps.lorenzGraphical demonstration of the orbit around theLorenz chaotic attractor.5-295Programming with MATLABMATLAB Visualization Demonstration Programs (Continued)pennySeveral views of the penny data.vibesVibrating L-shaped membrane movie.xfourierGraphical demonstration of Fourier series expansion.xpkleinKlein bottle demo.xpsoundDemonstration of MATLAB’s sound capability.MATLAB Language Demonstration Programsgraf3dDemonstration of Handle Graphics for surface plots.hndlaxisDemonstration of Handle Graphics for axes.hndlgrafDemonstration of Handle Graphics for line plots.xplangIntroduction to the MATLAB language.MATLAB ODE Suite Demonstration Programs5-30a2odeStiff problem, linear with real eigenvalues.a3odeStiff problem, linear with real eigenvalues.b5odeStiff problem, linear with complex eigenvalues.ballodeEquations of motion for a bouncing ball used byBALLDEMO.besslodeBessel’s equation of order 0 used by BESSLDEMO.brussodeStiff problem, modelling a chemical reaction(Brusselator).buiodeStiff problem, analytical solution due to Bui.chm6odeStiff problem CHM6 from Enright and Hull.Demonstration Programs Included with MATLABMATLAB ODE Suite Demonstration Programs (Continued)chm7odeStiff problem CHM7 from Enright and Hull.chm9odeStiff problem CHM9 from Enright and Hull.d1odeStiff problem, nonlinear with real eigenvalues.fem1odeStiff problem with a time-dependent mass matrix.fem2odeStiff problem with a time-independent mass matrix.gearodeStiff problem due to Gear as quoted by van derHouwen.hb1odeStiff problem 1 of Hindmarsh and Byrne.hb2odeStiff problem 2 of Hindmarsh and Byrne.hb3odeStiff problem 3 of Hindmarsh and Byrne.odedemoDemonstration of the ODE suite integrators.orbitodeRestricted 3 body problem used by ORBITDEMO.orbt2odeNonstiff problem D5 of Hull et al.rigidodeEuler equations of a rigid body without external forces.sticodeSpring-driven mass stuck to surface, used by STICDEMO.vdpodeParameterizable van der Pol equation (stiff for large µ).MATLAB Gallery Demonstration ProgramscrullerGraphical demonstration of a cruller.klein1Graphical demonstration of a Klein bottle.knotTube surrounding a three-dimensional knot.logoGraphical demonstration of the MATLAB L-shapedmembrane logo.5-315Programming with MATLABMATLAB Gallery Demonstration Programs (Continued)modesGraphical demonstration of 12 modes of the L-shapedmembrane.quivdemoGraphical demonstration of the quiver function.spharm2Graphical demonstration of spherical surfaceharmonic.tori4Graphical demonstration of four-linked, unknotted tori.finddemoCommand that finds available demos for individualtoolboxes.helpfunUtility function for displaying help text conveniently.membraneThe MathWorks logo.peaksSample function of two variables.pltmatCommand that displays a matrix in a figure window.MATLAB Game Demonstration ProgramsbblwrapBubblewrap.lifeConway’s Game of Life.somaSoma cube.xpbombsMinesweeper game.MATLAB Miscellaneous Demonstration Programs5-32codecAlphabet transposition coder/decoder.crulspinSpinning cruller movie.logospinMovie of the MathWorks logo spinning.Demonstration Programs Included with MATLABMATLAB Miscellaneous Demonstration Programs (Continued)makevaseDemonstration of a surface of revolution.quatdemoQuaternion rotation.spinnerColorful lines spinning through space.travelTraveling salesman problem.trussAnimation of a bending bridge truss.wrldtrvGreat circle flight routes around the globe.xphideVisual perception of objects in motion.xpquadSuperquadrics plotting demonstration.MATLAB Helper Functions Demonstration ProgramsbuckyGraph of the Buckminster Fuller geodesic dome.cmdlnbgnSet up for command line demos.cmdlnendClean up after command line demos.cmdlnwinDemo gateway routine for running command linedemos.finddemoCommand that finds available demos for individualtoolboxes.helpfunUtility function for displaying help text conveniently.membraneThe MathWorks logo.peaksSample function of two variables.pltmatCommand that displays a matrix in a figure window.5-335Programming with MATLABGetting More InformationThe MathWorks Web site (www.mathworks.com) contains numerous M-filesthat have been written by users and MathWorks staff.

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
5259
Авторов
на СтудИзбе
421
Средний доход
с одного платного файла
Обучение Подробнее