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

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

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

There are six equations in three unknowns,21 t1 t1y1y2y3y4y521 t2 t2a021 t3 t3=× a121 t4 t4a2y621 t5 t521 t6 t6represented by the 6-by-3 matrixX = [ones(size(t))tt.^2]X =1.00001.00001.00001.00001.00001.000000.30000.80001.10001.60002.300000.09000.64001.21002.56005.2900The solution is found with the backslash operator.a = X\ya =0.53180.9191- 0.238713-18Regression and Curve FittingThe second-order polynomial model of the data is thereforey = 0.5318 + 0.919 ( 1 )t – 0.2387t 2Now evaluate the model at regularly spaced points and overlay the originaldata in a plot.T = (0:0.1:2.5)';Y = [ones(size(T)) T T.^2]*a;plot(T,Y,'-',t,y,'o'), grid on1.51.41.31.21.110.90.80.70.60.500.511.522.5Clearly this fit does not perfectly approximate the data.

We could eitherincrease the order of the polynomial fit, or explore some other functional formto get a better approximation.Linear-in-the-Parameters RegressionInstead of a polynomial function, we could try using a function that islinear-in-the-parameters. In this case, consider the exponential functiony = a0 + a1 e–t+ a 2 te–tThe unknown coefficients a 0 , a 1 , and a 2 , are computed by performing a leastsquares fit.

Construct and solve the set of simultaneous equations by forming13-1913Data Analysis and Statisticsthe regression matrix, X, and solving for the coefficients using the backslashoperator.X = [ones(size(t))a = X\yexp(-t)t.*exp(-t)];a =1.3974- 0.89880.4097The fitted model of the data is, therefore,y = 1.3974 – 0.8988 e–t+ 0.4097 te–tNow evaluate the model at regularly spaced points and overlay the originaldata in a plot.T = (0:0.1:2.5)';Y = [ones(size(T)) exp(-T) T.*exp(-T)]*a;plot(T,Y,'-',t,y,'o'), grid on1.51.41.31.21.110.90.80.70.60.500.511.522.5This is a much better fit than the second-order polynomial function.13-20Regression and Curve FittingMultiple RegressionIf y is a function of more than one independent variable, the matrix equationsthat express the relationships among the variables can be expanded toaccommodate the additional data.Suppose we measure a quantity y for several values of parameters x 1 and x 2 .The observations are entered asx1 = [.2 .5 .6 .8 1.0 1.1]';x2 = [.1 .3 .4 .9 1.1 1.4]';y = [.17 .26 .28 .23 .27 .24]';A multivariate model of the data isy = a0 + a1 x1 + a2 x2Multiple regression solves for unknown coefficients a 0 , a 1 , and a 2 , byperforming a least squares fit.

Construct and solve the set of simultaneousequations by forming the regression matrix, X, and solving for the coefficientsusing the backslash operator.X = [ones(size(x1))a = X\yx1x2];a =0.10180.4844-0.2847The least squares fit model of the data isy = 0.1018 + 0.4844 x 1 – 0.2847 x 2To validate the model, find the maximum of the absolute value of the deviationof the data from the model.Y = X*a;MaxErr = max(abs(Y - y))MaxErr =0.0038This is sufficiently small to be confident the model reasonably fits the data.13-2113Data Analysis and StatisticsCase Study: Curve FittingThis section provides an overview of some of MATLAB’s basic data analysiscapabilities in the form of a case study.

The examples that follow work with acollection of census data, using MATLAB functions to experiment with fittingcurves to the data:• Polynomial fit• Analyzing residuals• Exponential fit• Error boundsThis section also tells you how to use the Basic Fitting interface to performcurve fitting tasks.Loading the DataThe file census.mat contains U.S. population data for the years 1790 through1990.

Load it into MATLAB.load censusYour workspace now contains two new variables, cdate and pop:• cdate is a column vector containing the years from 1790 to 1990 inincrements of 10.• pop is a column vector with the U.S. population figures that correspond to theyears in cdate.Polynomial FitA first try in fitting the census data might be a simple polynomial fit. TwoMATLAB functions help with this process.Curve Fitting Function Summary13-22FunctionDescriptionpolyfitPolynomial curve fit.polyvalEvaluation of polynomial fit.Case Study: Curve FittingMATLAB’s polyfit function generates a “best fit” polynomial (in the leastsquares sense) of a specified order for a given set of data. For a polynomial fitof the fourth-orderp = polyfit(cdate,pop,4)Warning: Polynomial is badly conditioned.

Remove repeated datapoints or try centering and scaling as described in HELP POLYFIT.p =1.0e+05 ∗0.0000-0.00000.0000-0.0126 6.0020The warning arises because the polyfit function uses the cdate values as thebasis for a matrix with very large values (it creates a Vandermonde matrix inits calculations – see the polyfit M-file for details).

The spread of the cdatevalues results in scaling problems. One way to deal with this is to normalizethe cdate data.Preprocessing: Normalizing the DataNormalization is a process of scaling the numbers in a data set to improve theaccuracy of the subsequent numeric computations. A way to normalize cdateis to center it at zero mean and scale it to unit standard deviation.sdate = (cdate - mean(cdate))./std(cdate)Now try the fourth-degree polynomial model using the normalized data.p = polyfit(sdate,pop,4)p =0.70470.921023.470673.859862.2285Evaluate the fitted polynomial at the normalized year values, and plot the fitagainst the observed data points.pop4 = polyval(p,sdate);plot(cdate,pop4,'-',cdate,pop,'+'), grid on13-2313Data Analysis and Statistics300250200150100500175018001850190019502000Another way to normalize data is to use some knowledge of the solution andunits.

For example, with this data set, choosing 1790 to be year zero would alsohave produced satisfactory results.Analyzing ResidualsA measure of the “goodness” of fit is the residual, the difference between theobserved and predicted data. Compare the residuals for the various fits, usingnormalized cdate values.

It’s evident from studying the fit plots and residualsthat it should be possible to do better than a simple polynomial fit with thisdata set.13-24Case Study: Curve FittingComparison Plots of Fit and ResidualFitResidualsp1 = polyfit(sdate,pop,1);pop1 = polyval(p1,sdate);plot(cdate,pop1,'b-',cdate,pop,'g+')res1 = pop - pop1;figure, plot(cdate,res1,'g+')25020050Linear fit appears unsatisfactory– note negative populationvalues at lower end of scale.Residuals of linear fit showstrongly patterned behavior.40301502010010050−100−20−50175018001850190019502000p = polyfit(sdate,pop,2);pop2 = polyval(p,sdate);plot(cdate,pop2,'b-',cdate,pop,'g+')250200−30175018001850190019502000res2 = pop - pop2;figure, plot(cdate,res2,'g+')6Quadratic polynomial providesbetter fit to data points.421500−2100Residuals still appear stronglypatterned.−450−60175018001850190019502000−817501800185019001950200013-2513Data Analysis and StatisticsComparison Plots of Fit and Residual (Continued)FitResidualsp = polyfit(sdate,pop,4);pop4 = polyval(p,sdate);plot(cdate,pop4,'b-',cdate,pop,'g+')res4 = pop - pop4;figure, plot(cdate,res4,'g+')3006250200Fourth-degree model provideslittle improvement – note thatcurve still begins to turn upwardat lower end of plot.420150−2Residuals still appear stronglypatterned.100−4500175013-26−618001850190019502000−8175018001850190019502000Case Study: Curve FittingExponential FitBy looking at the population data plots on the previous pages, the populationdata curve is somewhat exponential in appearance.

To take advantage of this,let’s try to fit the logarithm of the population values, again working withnormalized year values.logp1 = polyfit(sdate,log10(pop),1);logpred1 = 10.^polyval(logp1,sdate);semilogy(cdate,logpred1,'-',cdate,pop,'+');grid on310210110010175018001850190019502000Now try the logarithm analysis with a second-order model.logp2 = polyfit(sdate,log10(pop),2);logpred2 = 10.^polyval(logp2,sdate);semilogy(cdate,logpred2,'-',cdate,pop,'+'); grid on13-2713Data Analysis and Statistics310210110010175018001850190019502000This is a more accurate model.

The upper end of the plot appears to taper off,while the polynomial fits in the previous section continue, concave up, toinfinity.13-28Case Study: Curve FittingCompare the residuals for the second-order logarithmic model.Residuals in Log Population ScaleResiduals in Population Scalelogres2 = log10(pop) –polyval(logp2,sdate);plot(cdate,logres2,'+')r = pop – 10.^(polyval(logp2,sdate));plot(cdate,r,'+')0.03100.0250.0100−0.01−5−0.02−10−0.03−0.04175018001850190019502000−15175018001850190019502000The residuals are more random than for the simple polynomial fit.

As might beexpected, the residuals tend to get larger in magnitude as the populationincreases. But overall, the logarithmic model provides a more accurate fit to thepopulation data.13-2913Data Analysis and StatisticsError BoundsError bounds are useful for determining if your data is reasonably modeled byYou can obtain the error bounds by passing an optional second outputparameter from polyfit as an input parameter to polyval.This example uses the census demo data and normalizes the data by centeringit at zero mean and scaling it to unit standard deviation.

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

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

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

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