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

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

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

Its syntax is:for index = start:increment:endstatementsendThe default increment is 1. You can specify any increment, including a negativeone. For positive indices, execution terminates when the value of the indexexceeds the end value; for negative increments, it terminates when the index isless than the end value.For example, this loop executes five times.for i = 2:6x(i) = 2*x(i–1);endYou can nest multiple for loops.for i = 1:mfor j = 1:nA(i,j) = 1/(i + j – 1);endendNote You can often speed up the execution of MATLAB code by replacing forand while loops with vectorized code.

See “Vectorization of Loops” on page1-91 for details.Using Arrays as IndicesThe index of a for loop can be an array. For example, consider an m-by-n arrayA. The statementfor i = Astatementsend17-40Flow Controlsets i equal to the vector A(:,k). For the first loop iteration, k is equal to 1; forthe second k is equal to 2, and so on until k equals n. That is, the loop iteratesfor a number of times equal to the number of columns in A. For each iteration,i is a vector containing one of the columns of A.continueThe continue statement passes control to the next iteration of the for or whileloop in which it appears, skipping any remaining statements in the body of theloop.

In nested loops, continue passes control to the next iteration of the foror while loop enclosing it.The example below shows a continue loop that counts the lines of code in thefile, magic.m, skipping all blank lines and comments. A continue statement isused to advance to the next line in magic.m without incrementing the countwhenever a blank line or comment line is encountered.fid = fopen('magic.m','r');count = 0;while ~feof(fid)line = fgetl(fid);if isempty(line) | strncmp(line,'%',1)continueendcount = count + 1;enddisp(sprintf('%d lines',count));breakThe break statement terminates the execution of a for loop or while loop.When a break statement is encountered, execution continues with the nextstatement outside of the loop.

In nested loops, break exits from the innermostloop only.The example below shows a while loop that reads the contents of the file fft.minto a MATLAB character array. A break statement is used to exit the whileloop when the first empty line is encountered. The resulting character arraycontains the M-file help for the fft program.17-4117M-File Programmingfid = fopen('fft.m','r');s = '';while ~feof(fid)line = fgetl(fid);if isempty(line)breakends = strvcat(s,line);enddisp(s)try ... catchThe general form of a try ... catch statement sequence istry,statement,...,statement,catch,statement,...,statement,endIn this sequence the statements between try and catch are executed until anerror occurs.

The statements between catch and end are then executed. Uselasterr to see the cause of the error. If an error occurs between catch and end,MATLAB terminates execution unless another try ... catch sequence has beenestablished.returnreturn terminates the current sequence of commands and returns control tothe invoking function or to the keyboard. return is also used to terminatekeyboard mode. A called function normally transfers control to the functionthat invoked it when it reaches the end of the function. return may be insertedwithin the called function to force an early termination and to transfer controlto the invoking function.17-42SubfunctionsSubfunctionsFunction M-files can contain code for more than one function.

The first functionin the file is the primary function, the function invoked with the M-file name.Additional functions within the file are subfunctions that are only visible to theprimary function or other subfunctions in the same file.Each subfunction begins with its own function definition line. The functionsimmediately follow each other. The various subfunctions can occur in anyorder, as long as the primary function appears first.function [avg,med] = newstats(u) % Primary function% NEWSTATS Find mean and median with internal functions.n = length(u);avg = mean(u,n);med = median(u,n);function a = mean(v,n)% Calculate average.a = sum(v)/n;% Subfunctionfunction m = median(v,n)% Calculate median.w = sort(v);if rem(n,2) == 1m = w((n+1)/2);elsem = (w(n/2)+w(n/2+1))/2;end% SubfunctionThe subfunctions mean and median calculate the average and median of theinput list.

The primary function newstats determines the length of the list andcalls the subfunctions, passing to them the list length n. Functions within thesame M-file cannot access the same variables unless you declare them as globalwithin the pertinent functions, or pass them as arguments. In addition, thehelp facility can only access the primary function in an M-file.When you call a function from within an M-file, MATLAB first checks the fileto see if the function is a subfunction.

It then checks for a private function(described in the following section) with that name, and then for a standardM-file on your search path. Because it checks for a subfunction first, you can17-4317M-File Programmingsupersede existing M-files using subfunctions with the same name, forexample, mean in the above code.

Function names must be unique within anM-file, however.17-44Private FunctionsPrivate FunctionsPrivate functions are functions that reside in subdirectories with the specialname private. They are visible only to functions in the parent directory. Forexample, assume the directory newmath is on the MATLAB search path. Asubdirectory of newmath called private can contain functions that only thefunctions in newmath can call.

Because private functions are invisible outside ofthe parent directory, they can use the same names as functions in otherdirectories. This is useful if you want to create your own version of a particularfunction while retaining the original in another directory. Because MATLABlooks for private functions before standard M-file functions, it will find aprivate function named test.m before a nonprivate M-file named test.m.You can create your own private directories simply by creating subdirectoriescalled private using the standard procedures for creating directories or folderson your computer.

Do not place these private directories on your path.17-4517M-File ProgrammingSubscripting and IndexingSubscriptingThis section explains how to use subscripting to access and assign to elementsof a MATLAB matrix. It covers the following:• Accessing Single Elements of a Matrix• Accessing Multiple Elements of a Matrix• Expanding the Size of a Matrix• Deleting Rows and Columns• Concatenating MatricesAccessing Single Elements of a MatrixThe element in row i and column j of A is denoted by A(i,j). For example,suppose A = magic(4), Then A(4,2) is the number in the fourth row andsecond column.

For our magic square, A(4,2) is 14.A = magic(4)A =16594211714310615138121A(4,2)ans =14It 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.17-46Subscripting and IndexingSo, for our magic square, A(8) is another way of referring to the value 14 storedin A(4,2).A(8)ans =14Accessing Multiple Elements of a MatrixIt is possible to compute the sum of the elements in the fourth column of A bytypingA(1,4) + A(2,4) + A(3,4) + A(4,4)You can reduce the size of this expression using the colon operator.

Subscriptexpressions involving colons refer to portions of a matrix.A(1:m,n)refers to the elements in rows 1 through m of column n of the A matrix. Usingthis notation, you can compute the sum of the fourth column of A moresuccinctly.sum(A(1:4,4))The colon by itself refers to all the elements in a row or column of a matrix. Thekeyword end refers to the last row or column. Using the following syntax, youcan compute this same column sum without having to specify row and columnnumbers.sum(A(:,end))ans =34By adding an additional colon operator, you can refer to nonconsecutiveelements in a matrix. The m:3:n in this expression means to make theassignment to every third element in the matrix.17-4717M-File ProgrammingB = A;B(1:3:end) = -10B =-1059-10211-10143-10615-10812-10You can repeatedly access an array element using the ones function.

To createa new 2-by-6 matrix out of the the 9th element of A,B = A(9*ones(2,6))B =333333333333Expanding the Size of a MatrixIf you try to access an element outside of the matrix, it is an errorB = A(4,5)Index exceeds matrix dimensionsHowever, if you store a value in an element outside of the matrix, the size ofthe matrix increases to accommodate the new element.B = A;B(4,5) = 17B =1659417-4821171431061513812100017Subscripting and IndexingSimilarly, you can expand a matrix by assigning to a series of matrix elements.B(2:5,5:6) = 5B =1659402117140310615013812100555505555Deleting Rows and ColumnsYou can delete rows and columns from a matrix using just a pair of squarebrackets. Start withX = A;Then, to delete the second column of X, useX(:,2) = []This changes X toX =16594310615138121If you delete a single element from a matrix, the result isn’t a matrix anymore.So expressions likeX(1,2) = []result in an error.

However, using a single subscript deletes a single element,or sequence of elements, and reshapes the remaining elements into a rowvector. SoX(2:2:10) = []17-4917M-File Programmingresults inX =1693613121Concatenating MatricesConcatenation is the process of joining small matrices together to make biggerones. In fact, you made your first matrix by concatenating its individualelements. The pair of square brackets, [], is the concatenation operator. For anexample, start with the 4-by-4 magic square, A, and formB = [A A+32;A+48 A+16]The result is an 8-by-8 matrix, obtained by joining the four submatrices.B =16594645357522117145059556231061551585463138121615660494837413632212520344339461827233035423847192622314540443329242817This matrix is half way to being another magic square. Its elements are arearrangement of the integers 1:64.

Its column sums are the correct value foran 8-by-8 magic square.sum(B)ans =260260260260260260260260But, its row sums, sum(B')', are not all the same. Further manipulation isnecessary to make this a valid 8-by-8 magic square.17-50Subscripting and IndexingAdvanced IndexingMATLAB stores each array as a column of values regardless of the actualdimensions.

This column consists of the array columns, appended end to end.For example, MATLAB storesA = [2 6 9; 4 2 8; 3 0 1]as243620981Accessing A with a single subscript indexes directly into the storage column.A(3) accesses the third value in the column, the number 3. A(7) accesses theseventh value, 9, and so on.If you supply more subscripts, MATLAB calculates an index into the storagecolumn based on the dimensions you assigned to the array. For example,assume a two-dimensional array like A has size [d1 d2], where d1 is thenumber of rows in the array and d2 is the number of columns. If you supply twosubscripts (i,j) representing row-column indices, the offset is(j–1)*d1+iGiven the expression A(3,2), MATLAB calculates the offset into A’s storagecolumn as (2-1)*3+3, or 6. Counting down six elements in the column accessesthe value 0.Indexing Into Multidimensional ArraysThis storage and indexing scheme also extends to multidimensional arrays.

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

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

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

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