Using MATLAB (779505), страница 50

Файл №779505 Using MATLAB (Using MATLAB) 50 страницаUsing MATLAB (779505) страница 502017-12-27СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 50)

The example thenuses polyfit and polyval to produce error bounds for a second-orderpolynomial model. Year values are normalized. This code uses an interval of±2∆, corresponding to a 95% confidence interval.load censussdate = (cdate - mean(cdate))./std(cdate)[p2,S2] = polyfit(sdate,pop,2);[pop2,del2] = polyval(p2,sdate,S2);plot(cdate,pop,'+',cdate,pop2,'g-',cdate,pop2+2*del2,'r:',...cdate,pop2-2∗del2,'r:'), grid on300250200150100500−50175013-3018001850190019502000Case Study: Curve FittingThe Basic Fitting InterfaceMATLAB supports curve fitting through the Basic Fitting interface.

Using thisinterface, you can quickly perform many curve fitting tasks within the sameeasy-to-use environment. The interface is designed so that you can:• Fit data using a spline interpolant, a shape-preserving interpolant, or apolynomial up to degree 10.• Plot multiple fits simultaneously for a given data set.• Plot the fit residuals.• Examine the numerical results of a fit.• Evaluate (interpolate or extrapolate) a fit.• Annotate the plot with the numerical fit results and the norm of residuals.• Save the fit and evaluated results to the MATLAB workspace.Depending on your specific curve fitting application, you can use the BasicFitting interface, the command line functionality, or both.You can use the Basic Fitting interface onlywith 2-D data. However, if you plot multipledata sets as a subplot, and at least one data setis 2-D, then the interface is enabled.Note For the HP, IBM, and SGI platforms, the Basic Fitting interface is notsupported for Release 12.Overview of the Basic Fitting InterfaceThe full Basic Fitting interface is shown below.

To reproduce this state, followthese three steps:1 Plot some data.2 Select Basic Fitting from the Tools menu.3 Click thebutton twice.13-3113Data Analysis and StatisticsSelect data – This parameter list is populated with the names of all the datasets you display in the figure window associated with the Basic Fittinginterface.Use this list to select the current data set.

The current data set is defined asthe data set that is to be fit. You can fit only one data set at a time. However,you can perform multiple fits for the current data set. Use the Plot Editor tochange the name of a data set.Center and scale X data – If checked, the data is centered at zero mean andscaled to unit standard deviation. You may need to center and scale your datato improve the accuracy of the subsequent numerical computations. A warningis displayed if a fit produces results that may be inaccurate.Plot fits – This panel allows you to visually explore one or more fits to thecurrent data set:• Check to display fits on figure – Select the fits you want to display for thecurrent data set. There are two types of fits to choose from: interpolants andpolynomials. The spline interpolant uses the spline function, while the13-32Case Study: Curve Fittingshape-preserving interpolant uses the pchip function.

Refer to the pchiponline help for a comparison of these two functions. The polynomial fits usethe polyfit function. You can choose as many fits for a given data set as youwant.If your data set has N points, then you should use polynomials with, at most,N coefficients. If your fit uses polynomials with more than N coefficients, theinterface automatically sets a sufficient number of coefficients to 0 duringthe calculation so that the system is not underdetermined.• Show equations – If checked, the fit equation is displayed on the plot.- Significant digits – Select the significant digits associated with theequation display.• Plot residuals – If checked, the fit residuals are displayed.

The fit residualsare defined as the difference between the ordinate data point and theresulting fit for each abscissa data point. You can display the residuals as abar plot, as a scatter plot, or as a line plot in the same figure window as thedata or in a separate figure window. If you use subplots to plot multiple datasets, then residuals can be plotted only in a separate figure window.- Show norm of residuals – If checked, the norm of residuals are displayed.The norm of residuals is a measure of the goodness of fit, where a smallervalue indicates a better fit than a larger value.

It is calculated using thenorm function, norm(V,2), where V is the vector of residuals.Numerical results – This panel allows you to explore the numerical results ofa single fit to the current data set without plotting the fit:• Fit – Select the equation to fit to the current data set. The fit results aredisplayed in the list box below the menu. Note that selecting an equation inthis menu does not affect the state of the Plot fits panel.

Therefore, if youwant to display the fit in the data plot, you may need to select the associatedcheck box in Plot fits.• Coefficients and norm of residuals – Display the numerical results for theequation selected in Fit. Note that when you first open the NumericalResults panel, the results of the last fit you selected in Plot fits aredisplayed.• Save to workspace – Launch a dialog box that allows you to save the fitresults to workspace variables.• Find Y = f(X) – Interpolate or extrapolate the current fit.13-3313Data Analysis and Statistics- Enter value(s) – Enter a MATLAB expression to evaluate for the currentfit. The expression is evaluated after you press the Evaluate button, andthe results are displayed in the associated table.

The current fit isdisplayed in the Fit menu.- Save to workspace – Launch a dialog box that allows you to save theevaluated results to workspace variables.- Plot results – If checked, the evaluated results are displayed on the dataplot.Example: Using the Basic Fitting InterfaceThis example illustrates the features of the Basic Fitting interface by fitting acubic polynomial to the census data. You may want to repeat this exampleusing different equations and compare results. To launch the interface:1 Plot some data.plot(cdate,pop,'ro')2 Select Basic Fitting from the Tools menu in the figure.13-34Case Study: Curve FittingConfigure the Basic Fitting interface to:• Fit a cubic polynomial to the data.• Display the equation in the data plot.• Plot the fit residuals as a bar plot, and display the residuals as a subplot ofthe data figure window.• Display the norm of the residuals.This configuration is shown below.Current data setFit a cubic polynomial to the dataShow the equationPlot the residuals as a bar plot inthe data figure windowShow the norm of the residualsThe Plot fits panel allows you to visually explore multiple fits to the currentdata set.

For comparison, try fitting additional equations to the census data byselecting the appropriate check boxes. If an equation produces results that maybe numerically inaccurate, a warning is displayed. In this case, you shouldselect the Center and scale X data check box to improve the numericalaccuracy.13-3513Data Analysis and StatisticsThe resulting fit and the residuals are shown below.The plot legend indicates the name of the data set and the equation.

The legendis automatically updated as you add or remove data sets or fits. Additionally,fits are displayed using a default set of line styles and colors. You can changeany of the default plot settings using the Plot Editor. However, any changesyou make are undone if you subsequently perform another fit. To retainchanges, you should wait until after you have finished fitting your data.Note If you change the name of a data set in the legend, then the name isautomatically changed in the Select data menu.13-36Case Study: Curve FittingBy selecting theof the residuals.button, you can examine the fit coefficients and the normThe Fit menu allows you to explore numerical fit results for the current dataset without plotting the fit. For comparison, you can display the numericalresults for other fits by selecting the desired equation. Note that if you want todisplay a fit in the data plot, you have to select the associated check box in Plotfits.You can save the fit results to the MATLAB workspace by selecting the Saveto workspace button.13-3713Data Analysis and StatisticsThe fit structure is shown below.fit1fit1 =type: 'polynomial degree 3'coeff: [3.8555e-006 -0.0153 17.7815 -4.8519e+003]You may want to use this structure for subsequent display or analysis.

Forexample, you can use the saved coefficients and the polyval function toevaluate the cubic polynomial at the command line.By selecting thebutton again, you can evaluate the current fit at thespecified abscissa values. The current fit is displayed in the Fit menu. In thisexample, the population for the years 2000 to 2050 is evaluated in incrementsof 10, and then displayed in the data plot.13-38Case Study: Curve FittingThe evaluated data is shown below.You can save the evaluated data to the MATLAB workspace by selecting theSave to workspace button.13-3913Data Analysis and StatisticsDifference Equations and FilteringMATLAB has functions for working with difference equations and filters.These functions operate primarily on vectors.Vectors are used to hold sampled-data signals, or sequences, for signalprocessing and data analysis.

Характеристики

Тип файла
PDF-файл
Размер
6,57 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

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