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

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

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

These functions are located in the MATLAB datafun directory.This section also gives you some hints about using row and column data, andprovides some basic examples. This table lists the functions.Basic Data Analysis Function Summary13-8FunctionDescriptioncumprodCumulative product of elements.cumsumCumulative sum of elements.cumtrapzCumulative trapezoidal numerical integration.diffDifference function and approximate derivative.maxLargest component.meanAverage or mean value.medianMedian value.minSmallest component.prodProduct of elements.sortSort in ascending order.sortrowsSort rows in ascending order.stdStandard deviation.Basic Data Analysis FunctionsBasic Data Analysis Function Summary (Continued)FunctionDescriptionsumSum of elements.trapzTrapezoidal numerical integration.For information about calculating the maximum, minimum, mean, median,range, and standard deviation on plotted data, and creating plots of thesestatistics, see “Adding Plots of Data Statistics to a Graph” in the MATLABgraphics documentation.Working with Row and Column DataFor vector input arguments to these functions, it does not matter whether thevectors are oriented in row or column direction.

For array arguments, however,the functions operate column by column on the data in the array. This means,for example, that if you apply max to an array, the result is a row vectorcontaining the maximum values over each column.Note You can add more functions to this list using M-files, but when doing so,you must exercise care to handle the row-vector case. If you are writing yourown column-oriented M-files, check other M-files; for example, mean.m anddiff.m.Basic ExamplesContinuing with the vehicle traffic count example, the statementsmx = max(count)mu = mean(count)sigma = std(count)result inmx =11414525732.000046.541765.5833mu =13-913Data Analysis and Statisticssigma =25.370341.405768.0281To locate the index at which the minimum or maximum occurs, a second outputparameter can be specified.

For example,[mx,indx] = min(count)mx =797indx =22324shows that the lowest vehicle count is recorded at 02h00 for the firstobservation point (column one) and at 23h00 and 24h00 for the otherobservation points.You can subtract the mean from each column of the data using an outer productinvolving a vector of n ones.[n,p] = size(count)e = ones(n,1)x = count - e*muRearranging the data may help you evaluate a vector function over an entiredata set. For example, to find the smallest value in the entire data set, usemin(count(:))which producesans =7The syntax count(:) rearranges the 24-by-3 matrix into a 72-by-1 columnvector.13-10Basic Data Analysis FunctionsCovariance and Correlation CoefficientsMATLAB’s statistical capabilities include two functions for the computation ofcorrelation coefficients and covariance.Covariance and Correlation Coefficient Function SummaryFunctionDescriptioncovVariance of vector – measure of spread or dispersion ofsample variable.Covariance of matrix – measure of strength of linearrelationships between variables.Correlation coefficient – normalized measure of linearrelationship strength between variables.corrcoefCovariancecov returns the variance for a vector of data.

The variance of the data in thefirst column of count iscov(count(:,1))ans =643.6522For an array of data, cov calculates the covariance matrix. The variance valuesfor the array columns are arranged along the diagonal of the covariance matrix.The remaining entries reflect the covariance between the columns of theoriginal array. For an m-by-n matrix, the covariance matrix has size n-by-n.For example, the covariance matrix for count, cov(count), is arranged as222222222σ 11 σ 12 σ 13σ 21 σ 22 σ 23σ 31 σ 32 σ 3322σ ij = σ ji13-1113Data Analysis and StatisticsCorrelation Coefficientscorrcoef produces a matrix of correlation coefficients for an array of datawhere each row is an observation and each column is a variable.

Thecorrelation coefficient is a normalized measure of the strength of the linearrelationship between two variables. Uncorrelated data results in a correlationcoefficient of 0; equivalent data sets have a correlation coefficient of 1.For an m-by-n matrix, the correlation coefficient matrix has size n-by-n. Thearrangement of the elements in the correlation coefficient matrix correspondsto the location of the elements in the covariance matrix described above.For our traffic count examplecorrcoef(count)results inans =1.00000.93310.95990.93311.00000.95530.95990.95531.0000Clearly there is a strong linear correlation between the three traffic countsobserved at the three locations, as the results are close to 1.Finite DifferencesMATLAB provides three functions for finite difference calculations.FunctionDescriptiondiffDifference between successive elements of a vector.Numerical partial derivatives of a vector.gradientNumerical partial derivatives a matrix.del2Discrete Laplacian of a matrix.The diff function computes the difference between successive elements in anumeric vector.

That is, diff(X) is [X(2)-X(1) X(3)-X(2)...X(n)-X(n-1)]. So, for a vector A,A = [9 -2 3 0 1 5 4];13-12Basic Data Analysis Functionsdiff(A)ans =-115-314-1Besides computing the first difference, diff is useful for determining certaincharacteristics of vectors. For example, you can use diff to determine if avector is monotonic (elements are always either increasing or decreasing), or ifa vector has equally spaced elements.

This table describes a few different waysto use diff with a vector x.TestDescriptiondiff(x)==0Tests for repeated elements.all(diff(x)>0)Tests for monotonicity.all(diff(diff(x))==0)Tests for equally spaced vector elements.13-1313Data Analysis and StatisticsData PreprocessingThis section tells you how to work with• Missing values• Outliers and misplaced data pointsMissing ValuesThe special value, NaN, stands for Not-a-Number in MATLAB. IEEEfloating-point arithmetic convention specifies NaN as the result of undefinedexpressions such as 0/0.The correct handling of missing data is a difficult problem and often varies indifferent situations. For data analysis purposes, it is often convenient to useNaNs to represent missing values or data that are not available.MATLAB treats NaNs in a uniform and rigorous way. They propagate naturallythrough to the final result in any calculation.

Any mathematical calculationinvolving NaNs produces NaNs in the results.For example, consider a matrix containing the 3-by-3 magic square with itscenter element set to NaN.a = magic(3); a(2,2) = NaNa =8341NaN9672Compute a sum for each column in the matrix.sum(a)ans =15NaN15Any mathematical calculation involving NaNs propagates NaNs through to thefinal result as appropriate.13-14Data PreprocessingYou should remove NaNs from the data before performing statisticalcomputations.

Here are some ways to use isnan to remove NaNs from data.CodeDescriptioni = find(~isnan(x));x = x(i)Find indices of elements in vector that arenot NaNs, then keep only the non-NaNelements.x = x(find(~isnan(x)))Remove NaNs from vector.x = x(~isnan(x));Remove NaNs from vector (faster).x(isnan(x)) = [];Remove NaNs from vector.X(any(isnan(X)'),:) = [];Remove any rows of matrix X containingNaNs.Note You must use the special function isnan to find NaNs because, by IEEEarithmetic convention, the logical comparison, NaN == NaN always produces 0.You cannot use x(x==NaN) = [] to remove NaNs from your data.If you frequently need to remove NaNs, write a short M-file function.function X = excise(X)X(any(isnan(X)'),:) = [];Now, typingX = excise(X);accomplishes the same thing.Removing OutliersYou can remove outliers or misplaced data points from a data set in much thesame manner as NaNs.

For the vehicle traffic count data, the mean andstandard deviations of each column of the data aremu = mean(count)13-1513Data Analysis and Statisticssigma = std(count)mu =32.000046.541765.5833sigma =25.370341.405768.0281The number of rows with outliers greater than three standard deviations isobtained with[n,p] = size(count)outliers = abs(count - mu(ones(n, 1),:)) > 3*sigma(ones(n, 1),:);nout = sum(outliers)nout =100There is one outlier in the first column. Remove this entire observation withcount(any(outliers'),:) = [];13-16Regression and Curve FittingRegression and Curve FittingIt is often useful to find functions that describe the relationship between somevariables you have observed.

Identification of the coefficients of the functionoften leads to the formulation of an overdetermined system of simultaneouslinear equations. You can find these coefficients efficiently by using theMATLAB backslash operator.Suppose you measure a quantity y at several values of time t.t = [0 .3 .8 1.1 1.6 2.3]';y = [0.5 0.82 1.14 1.25 1.35 1.40]';plot(t,y,'o'), grid on1.41.31.21.110.90.80.70.60.500.511.522.5The following sections look at three ways of modeling the data:• Polynomial regression• Linear-in-the-parameters regression• Multiple regression13-1713Data Analysis and StatisticsPolynomial RegressionBased on the plot, it is possible that the data can be modeled by a polynomialfunctiony = a0 + a1 t + a2 t 2The unknown coefficients a0, a1, and a2 can be computed by doing a leastsquares fit, which minimizes the sum of the squares of the deviations of thedata from the model.

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

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

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

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