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

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

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

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

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

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

Arithmetic operations on arrays are doneelement-by-element. This means that addition and subtraction are the samefor arrays and matrices, but that multiplicative operations are different.MATLAB uses a dot, or decimal point, as part of the notation for multiplicativearray operations.3-213Manipulating MatricesThe list of operators includes:+Addition-Subtraction.*Element-by-element multiplication./Element-by-element division.\Element-by-element left division.^Element-by-element power.'Unconjugated array transposeIf the Dürer magic square is multiplied by itself with array multiplicationA.*Athe result is an array containing the squares of the integers from 1 to 16, in anunusual order.ans =256258116910036225412149196169641441Building TablesArray operations are useful for building tables.

Suppose n is the column vectorn = (0:9)';Thenpows = [n3-22n.^22.^n]More About Matrices and Arraysbuilds a table of squares and powers of two.pows =012345678901491625364964811248163264128256512The elementary math functions operate on arrays element by element. Soformat short gx = (1:0.1:2)';logs = [x log10(x)]builds a table of logarithms.logs =1.01.11.21.31.41.51.61.71.81.92.000.041390.079180.113940.146130.176090.204120.230450.255270.278750.301033-233Manipulating MatricesMultivariate DataMATLAB uses column-oriented analysis for multivariate statistical data.

Eachcolumn in a data set represents a variable and each row an observation. The(i,j)th element is the ith observation of the jth variable.As an example, consider a data set with three variables:• Heart rate• Weight• Hours of exercise per weekFor five observations, the resulting array might look likeD =72816982751342011561481703.23.57.12.41.2The first row contains the heart rate, weight, and exercise hours for patient 1,the second row contains the data for patient 2, and so on. Now you can applymany of MATLAB’s data analysis functions to this data set. For example, toobtain the mean and standard deviation of each column:mu = mean(D), sigma = std(D)mu =75.8161.83.48sigma =5.630325.4992.2107For a list of the data analysis functions available in MATLAB, typehelp datafunIf you have access to the Statistics Toolbox, typehelp stats3-24More About Matrices and ArraysScalar ExpansionMatrices and scalars can be combined in several different ways.

For example,a scalar is subtracted from a matrix by subtracting it from each element. Theaverage value of the elements in our magic square is 8.5, soB = A - 8.5forms a matrix whose column sums are zero.B =7.5-3.50.5-4.5-5.51.5-2.56.5-6.52.5-1.55.54.5-0.53.5-7.5sum(B)ans =0000With scalar expansion, MATLAB assigns a specified scalar to all indices in arange. For example,B(1:2,2:3) = 0zeros out a portion of BB =7.5-3.50.5-4.500-2.56.500-1.55.54.5-0.53.5-7.53-253Manipulating MatricesLogical SubscriptingThe logical vectors created from logical and relational operations can be usedto reference subarrays. Suppose X is an ordinary matrix and L is a matrix of thesame size that is the result of some logical operation. Then X(L) specifies theelements of X where the elements of L are nonzero.This kind of subscripting can be done in one step by specifying the logicaloperation as the subscripting expression.

Suppose you have the following set ofdata.x =2.1 1.7 1.6 1.5 NaN 1.9 1.8 1.5 5.1 1.8 1.4 2.2 1.6 1.8The NaN is a marker for a missing observation, such as a failure to respond toan item on a questionnaire. To remove the missing data with logical indexing,use finite(x), which is true for all finite numerical values and false for NaNand Inf.x = x(finite(x))x =2.1 1.7 1.6 1.5 1.9 1.8 1.5 5.1 1.8 1.4 2.2 1.6 1.8Now there is one observation, 5.1, which seems to be very different from theothers.

It is an outlier. The following statement removes outliers, in this casethose elements more than three standard deviations from the mean.x = x(abs(x-mean(x)) <= 3*std(x))x =2.1 1.7 1.6 1.5 1.9 1.8 1.5 1.8 1.4 2.2 1.6 1.8For another example, highlight the location of the prime numbers in Dürer’smagic square by using logical indexing and scalar expansion to set thenonprimes to 0.A(~isprime(A)) = 0A =05003-2630002117013000More About Matrices and ArraysThe find FunctionThe find function determines the indices of array elements that meet a givenlogical condition. In its simplest form, find returns a column vector of indices.Transpose that vector to obtain a row vector of indices. For example,k = find(isprime(A))'picks out the locations, using one-dimensional indexing, of the primes in themagic square.k =259101113Display those primes, as a row vector in the order determined by k, withA(k)ans =53211713When you use k as a left-hand-side index in an assignment statement, thematrix structure is preserved.A(k) = NaNA =16NaN94NaN10615NaNNaNNaN14NaN81213-273Manipulating MatricesControlling Command Window Input and OutputSo far, you have been using the MATLAB command line, typing commands andexpressions, and seeing the results printed in the Command Window.

Thissection describes how to:• Control the appearance of the output values• Suppress output from MATLAB commands• Enter long commands at the command line• Edit the command lineThe format CommandThe format command controls the numeric format of the values displayed byMATLAB.

The command affects only how numbers are displayed, not howMATLAB computes or saves them. Here are the different formats, togetherwith the resulting output produced from a vector x with components ofdifferent magnitudes.Note To ensure proper spacing, use a fixed-width font, such as Fixedsys orCourier.x = [4/3 1.2345e-6]format short1.33330.0000format short e1.3333e+0001.2345e-006format short g1.33333-281.2345e-006Controlling Command Window Input and Outputformat long1.333333333333330.00000123450000format long e1.333333333333333e+0001.234500000000000e-006format long g1.333333333333331.2345e-006format bank1.330.00format rat4/31/810045format hex3ff55555555555553eb4b6231abfd271If the largest element of a matrix is larger than 103 or smaller than 10-3,MATLAB applies a common scale factor for the short and long formats.In addition to the format commands shown aboveformat compactsuppresses many of the blank lines that appear in the output.

This lets youview more information on a screen or window. If you want more control overthe output format, use the sprintf and fprintf functions.3-293Manipulating MatricesSuppressing OutputIf you simply type a statement and press Return or Enter, MATLABautomatically displays the results on screen. However, if you end the line witha semicolon, MATLAB performs the computation but does not display anyoutput. This is particularly useful when you generate large matrices.

Forexample,A = magic(100);Entering Long Command LinesIf a statement does not fit on one line, use three periods, ..., followed byReturn or Enter to indicate that the statement continues on the next line. Forexample,s = 1 -1/2 + 1/3 -1/4 + 1/5 - 1/6 + 1/7 ...- 1/8 + 1/9 - 1/10 + 1/11 - 1/12;Blank spaces around the =, +, and - signs are optional, but they improvereadability.Command Line EditingVarious arrow and control keys on your keyboard allow you to recall, edit, andreuse commands you have typed earlier. For example, suppose you mistakenlyenterrho = (1 + sqt(5))/2You have misspelled sqrt. MATLAB responds withUndefined function or variable 'sqt'.Instead of retyping the entire line, simply press the ↑ key.

The misspelledcommand is redisplayed. Use the ← key to move the cursor over and insert themissing r. Repeated use of the ↑ key recalls earlier lines. Typing a fewcharacters and then the ↑ key finds a previous line that begins with thosecharacters. You can also copy previously executed commands from theCommand History. For more information, see “Command History” on page 2-7.3-30Controlling Command Window Input and OutputThe list of available command line editing keys is different on differentcomputers.

Experiment to see which of the following keys is available on yourmachine. (Many of these keys will be familiar to users of the Emacs editor.)↑Ctrl+pRecall previous line↓Ctrl+nRecall next line←Ctrl+bMove back one character→Ctrl+fMove forward one characterCtrl+→Ctrl+rMove right one wordCtrl+←Ctrl+lMove left one wordHomeCtrl+aMove to beginning of lineEndCtrl+eMove to end of lineEscCtrl+uClear lineDelCtrl+dDelete character at cursorBackspaceCtrl+hDelete character before cursorCtrl+kDelete to end of line3-313Manipulating Matrices3-324GraphicsBasic Plotting. .

. . . . . . . . . . . . . . . . . 4-2Editing Plots. . . . . . . . . . . . . . . . . . . 4-14Mesh and Surface Plots . . . . . . . . . . . . . . . 4-18Images. . . . . . . . . . . . . . . . . . . . . . 4-22Printing Graphics. . . . . . . . . . . . . . . . . 4-24Handle Graphics . . . . . . . . . . . . . . . . . . 4-26Graphics User Interfaces . . . . .

. . . . . . . . . 4-33Animations. . . . . . . . . . . . . . . . . . . . 4-344GraphicsBasic PlottingMATLAB has extensive facilities for displaying vectors and matrices asgraphs, as well as annotating and printing these graphs. This section describesa few of the most important graphics functions and provides examples of sometypical applications.Creating a PlotThe plot function has different forms, depending on the input arguments. If yis a vector, plot(y) produces a piecewise linear graph of the elements of yversus the index of the elements of y. If you specify two vectors as arguments,plot(x,y) produces a graph of y versus x.For example, these statements use the colon operator to create a vector of xvalues ranging from zero to 2π, compute the sine of these values, and plot theresult.x = 0:pi/100:2*pi;y = sin(x);plot(x,y)Now label the axes and add a title.

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