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

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

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

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

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

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

If you use another editor, you can still use the MATLAB Editor/Debugger for debugging, or you can use debugging functions, such as dbstop,which sets a breakpoint.If you just need to view the contents of an M-file, you can display it in theCommand Window by using the type function.2-14Other Development Environment FeaturesOther Development Environment FeaturesAdditional development environment features are:• Importing and Exporting Data – Techniques for bringing data created byother applications into the MATLAB workspace, including the ImportWizard, and packaging MATLAB workspace variables for use by otherapplications.• Improving M-File Performance – The Profiler is a tool that measures wherean M-file is spending its time.

Use it to help you make speed improvements.• Interfacing with Source Control Systems – Access your source control systemfrom within MATLAB, Simulink®, and Stateflow®.• Using Notebook – Access MATLAB’s numeric computation and visualizationsoftware from within a word processing environment (Microsoft Word).2-152Development Environment2-163Manipulating MatricesMatrices and Magic Squares . . . .

. . . . . . . . . 3-2Expressions . . . . . . . . . . . . . . . . . . . . 3-10Working with Matrices . . . . . . . . . . . . . . . 3-14More About Matrices and Arrays . . . . . . . . . . . 3-18Controlling Command Window Input and Output . . . 3-283Manipulating MatricesMatrices and Magic SquaresIn MATLAB, a matrix is a rectangular array of numbers. Special meaning issometimes attached to 1-by-1 matrices, which are scalars, and to matrices withonly one row or column, which are vectors. MATLAB has other ways of storingboth numeric and nonnumeric data, but in the beginning, it is usually best tothink of everything as a matrix.

The operations in MATLAB are designed to beas natural as possible. Where other programming languages work withnumbers one at a time, MATLAB allows you to work with entire matricesquickly and easily. A good example matrix, used throughout this book, appearsin the Renaissance engraving Melancholia I by the German artist and amateurmathematician Albrecht Dürer.3-2Matrices and Magic SquaresThis image is filled withmathematical symbolism, and ifyou look carefully, you will see amatrix in the upper rightcorner. This matrix is known asa magic square and wasbelieved by many in Dürer’stime to have genuinely magicalproperties. It does turn out tohave some fascinatingcharacteristics worth exploring.Entering MatricesThe best way for you to get started with MATLAB is to learn how to handlematrices.

Start MATLAB and follow along with each example.You can enter matrices into MATLAB in several different ways:• Enter an explicit list of elements.• Load matrices from external data files.• Generate matrices using built-in functions.• Create matrices with your own functions in M-files.Start by entering Dürer’s matrix as a list of its elements. You have only tofollow a few basic conventions:• Separate the elements of a row with blanks or commas.• Use a semicolon, ; , to indicate the end of each row.• Surround the entire list of elements with square brackets, [ ].To enter Dürer’s matrix, simply type in the Command WindowA = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]3-33Manipulating MatricesMATLAB displays the matrix you just entered.A =16594310615211714138121This exactly matches the numbers in the engraving.

Once you have entered thematrix, it is automatically remembered in the MATLAB workspace. You canrefer to it simply as A. Now that you have A in the workspace, take a look atwhat makes it so interesting. Why is it magic?sum, transpose, and diagYou’re probably already aware that the special properties of a magic squarehave to do with the various ways of summing its elements. If you take the sumalong any row or column, or along either of the two main diagonals, you willalways get the same number.

Let’s verify that using MATLAB. The firststatement to try issum(A)MATLAB replies withans =34343434When you don’t specify an output variable, MATLAB uses the variable ans,short for answer, to store the results of a calculation. You have computed a rowvector containing the sums of the columns of A.

Sure enough, each of thecolumns has the same sum, the magic sum, 34.How about the row sums? MATLAB has a preference for working with thecolumns of a matrix, so the easiest way to get the row sums is to transpose thematrix, compute the column sums of the transpose, and then transpose theresult. The transpose operation is denoted by an apostrophe or single quote, '.It flips a matrix about its main diagonal and it turns a row vector into a columnvector. SoA'produces3-4Matrices and Magic Squaresans =16321351011896712415141Andsum(A')'produces a column vector containing the row sumsans =34343434The sum of the elements on the main diagonal is easily obtained with the helpof the diag function, which picks off that diagonal.diag(A)producesans =161071andsum(diag(A))producesans =34The other diagonal, the so-called antidiagonal, is not so importantmathematically, so MATLAB does not have a ready-made function for it.

But afunction originally intended for use in graphics, fliplr, flips a matrix from leftto right.3-53Manipulating Matricessum(diag(fliplr(A)))ans =34You have verified that the matrix in Dürer’s engraving is indeed a magicsquare and, in the process, have sampled a few MATLAB matrix operations.The following sections continue to use this matrix to illustrate additionalMATLAB capabilities.SubscriptsThe element in row i and column j of A is denoted by A(i,j). For example,A(4,2) is the number in the fourth row and second column. For our magicsquare, A(4,2) is 15. So it is possible to compute the sum of the elements in thefourth column of A by typingA(1,4) + A(2,4) + A(3,4) + A(4,4)This producesans =34but is not the most elegant way of summing a single column.It is also possible to refer to the elements of a matrix with a single subscript,A(k).

This is the usual way of referencing row and column vectors. But it canalso apply to a fully two-dimensional matrix, in which case the array isregarded as one long column vector formed from the columns of the originalmatrix. So, for our magic square, A(8) is another way of referring to the value15 stored in A(4,2).If you try to use the value of an element outside of the matrix, it is an error.t = A(4,5)Index exceeds matrix dimensions.On the other hand, if you store a value in an element outside of the matrix, thesize increases to accommodate the newcomer.X = A;X(4,5) = 173-6Matrices and Magic SquaresX =1659431061521171413812100017The Colon OperatorThe colon, :, is one of MATLAB’s most important operators.

It occurs in severaldifferent forms. The expression1:10is a row vector containing the integers from 1 to 1012345678910To obtain nonunit spacing, specify an increment. For example,100:-7:50is10093867972655851and0:pi/4:piis00.78541.57082.35623.1416Subscript expressions involving colons refer to portions of a matrix.A(1:k,j)is the first k elements of the jth column of A. Sosum(A(1:4,4))computes the sum of the fourth column. But there is a better way. The colon byitself refers to all the elements in a row or column of a matrix and the keywordend refers to the last row or column.

Sosum(A(:,end))3-73Manipulating Matricescomputes the sum of the elements in the last column of A.ans =34Why is the magic sum for a 4-by-4 square equal to 34? If the integers from 1 to16 are sorted into four groups with equal sums, that sum must besum(1:16)/4which, of course, isans =34The magic FunctionMATLAB actually has a built-in function that creates magic squares of almostany size. Not surprisingly, this function is named magic.B = magic(4)B =16594211714310615138121This matrix is almost the same as the one in the Dürer engraving and has allthe same “magic” properties; the only difference is that the two middle columnsare exchanged.

To make this B into Dürer’s A, swap the two middle columns.A = B(:,[1 3 2 4])This says “for each of the rows of matrix B, reorder the elements in the order 1,3, 2, 4.” It producesA =165943-8310615211714138121Matrices and Magic SquaresWhy would Dürer go to the trouble of rearranging the columns when he couldhave used MATLAB’s ordering? No doubt he wanted to include the date of theengraving, 1514, at the bottom of his magic square.3-93Manipulating MatricesExpressionsLike most other programming languages, MATLAB provides mathematicalexpressions, but unlike most programming languages, these expressionsinvolve entire matrices.

The building blocks of expressions are:• Variables• Numbers• Operators• FunctionsVariablesMATLAB does not require any type declarations or dimension statements.When MATLAB encounters a new variable name, it automatically creates thevariable and allocates the appropriate amount of storage. If the variablealready exists, MATLAB changes its contents and, if necessary, allocates newstorage. For example,num_students = 25creates a 1-by-1 matrix named num_students and stores the value 25 in itssingle element.Variable names consist of a letter, followed by any number of letters, digits, orunderscores.

MATLAB uses only the first 31 characters of a variable name.MATLAB is case sensitive; it distinguishes between uppercase and lowercaseletters. A and a are not the same variable. To view the matrix assigned to anyvariable, simply enter the variable name.NumbersMATLAB uses conventional decimal notation, with an optional decimal pointand leading plus or minus sign, for numbers. Scientific notation uses the lettere to specify a power-of-ten scale factor. Imaginary numbers use either i or j asa suffix.

Some examples of legal numbers are39.63972381i3-10-991.60210e-20-3.14159j0.00016.02252e233e5iExpressionsAll numbers are stored internally using the long format specified by the IEEEfloating-point standard. Floating-point numbers have a finite precision ofroughly 16 significant decimal digits and a finite range of roughly 10-308 to10+308.OperatorsExpressions use familiar arithmetic operators and precedence rules.+Addition-Subtraction*Multiplication/Division\Left division (described in “Matrices and LinearAlgebra” in Using MATLAB)^Power'Complex conjugate transpose( )Specify evaluation orderFunctionsMATLAB provides a large number of standard elementary mathematicalfunctions, including abs, sqrt, exp, and sin. Taking the square root orlogarithm of a negative number is not an error; the appropriate complex resultis produced automatically.

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