Главная » Просмотр файлов » Matlab - Getting start

Matlab - Getting start (779439), страница 10

Файл №779439 Matlab - Getting start (Matlab - Getting start) 10 страницаMatlab - Getting start (779439) страница 102017-12-27СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

Specify a number of points, such asn = 20and a temperature or velocity, such ass = .02The best values for these two parameters depend upon the speed of yourparticular computer. Generate n random points with (x,y) coordinates between-1/2 and +1/2.x = rand(n,1)-0.5;y = rand(n,1)-0.5;Plot the points in a square with sides at -1 and +1. Save the handle for thevector of points and set its EraseMode to xor. This tells the MATLAB graphicssystem not to redraw the entire plot when the coordinates of one point arechanged, but to restore the background color in the vicinity of the point usingan “exclusive or” operation.h = plot(x,y,'.');axis([-1 1 -1 1])axis squaregrid offset(h,'EraseMode','xor','MarkerSize',18)Now begin the animation.

Here is an infinite while loop, which you caneventually exit by typing Ctrl+c. Each time through the loop, add a smallamount of normally distributed random noise to the coordinates of the points.4-34AnimationsThen, instead of creating an entirely new plot, simply change the XData andYData properties of the original plot.while 1drawnowx = x + s*randn(n,1);y = y + s*randn(n,1);set(h,'XData',x,'YData',y)endHow long does it take for one of the points to get outside of the square? Howlong before all of the points are outside the square?10.80.60.40.20−0.2−0.4−0.6−0.8−1−1−0.500.51Creating MoviesIf you increase the number of points in the Brownian motion example tosomething like n = 300 and s = .02, the motion is no longer very fluid; it takestoo much time to draw each time step.

It becomes more effective to save apredetermined number of frames as bitmaps and to play them back as a movie.4-354GraphicsFirst, decide on the number of frames, saynframes = 50;Next, set up the first plot as before, except using the default EraseMode(normal).x = rand(n,1)-0.5;y = rand(n,1)-0.5;h = plot(x,y,'.');set(h,'MarkerSize',18);axis([-1 1 -1 1])axis squaregrid offGenerate the movie and use getframe to capture each frame.for k = 1:nframesx = x + s*randn(n,1);y = y + s*randn(n,1);set(h,'XData',x,'YData',y)M(k) = getframe;endFinally, play the movie 30 times.movie(M,30)4-365Programming withMATLABFlow Control .

. . . . . . . . . . . . . . . . . . . 5-2Other Data Structures. . . . . . . . . . . . . . . 5-7Scripts and Functions. . . . . . . . . . . . . . . 5-17Demonstration Programs Included with MATLAB . . . 5-275Programming with MATLABFlow ControlMATLAB has several flow control constructs:• if statements• switch statements• for loops• while loops• continue statements• break statementsifThe if statement evaluates a logical expression and executes a group ofstatements when the expression is true.

The optional elseif and elsekeywords provide for the execution of alternate groups of statements. An endkeyword, which matches the if, terminates the last group of statements. Thegroups of statements are delineated by the four keywords – no braces orbrackets are involved.MATLAB’s algorithm for generating a magic square of order n involves threedifferent cases: when n is odd, when n is even but not divisible by 4, or when nis divisible by 4. This is described byif rem(n,2) ~= 0M = odd_magic(n)elseif rem(n,4) ~= 0M = single_even_magic(n)elseM = double_even_magic(n)endIn this example, the three cases are mutually exclusive, but if they weren’t, thefirst true condition would be executed.It is important to understand how relational operators and if statements workwith matrices.

When you want to check for equality between two variables, youmight useif A == B, ...5-2Flow ControlThis is legal MATLAB code, and does what you expect when A and B are scalars.But when A and B are matrices, A == B does not test if they are equal, it testswhere they are equal; the result is another matrix of 0’s and 1’s showingelement-by-element equality. In fact, if A and B are not the same size, then A ==B is an error.The proper way to check for equality between two variables is to use theisequal function,if isequal(A,B), ...Here is another example to emphasize this point. If A and B are scalars, thefollowing program will never reach the unexpected situation.

But for mostpairs of matrices, including our magic squares with interchanged columns,none of the matrix conditions A > B, A < B or A == B is true for all elementsand so the else clause is executed.if A > B'greater'elseif A < B'less'elseif A == B'equal'elseerror('Unexpected situation')endSeveral functions are helpful for reducing the results of matrix comparisons toscalar conditions for use with if, includingisequalisemptyallanyswitch and caseThe switch statement executes groups of statements based on the value of avariable or expression. The keywords case and otherwise delineate thegroups. Only the first matching case is executed.

There must always be an endto match the switch.5-35Programming with MATLABThe logic of the magic squares algorithm can also be described byswitch (rem(n,4)==0) + (rem(n,2)==0)case 0M = odd_magic(n)case 1M = single_even_magic(n)case 2M = double_even_magic(n)otherwiseerror('This is impossible')endNote Unlike the C language switch statement, MATLAB’s switch does notfall through. If the first case statement is true, the other case statements donot execute. So, break statements are not required.forThe for loop repeats a group of statements a fixed, predetermined number oftimes. A matching end delineates the statements.for n = 3:32r(n) = rank(magic(n));endrThe semicolon terminating the inner statement suppresses repeated printing,and the r after the loop displays the final result.It is a good idea to indent the loops for readability, especially when they arenested.for i = 1:mfor j = 1:nH(i,j) = 1/(i+j);endend5-4Flow ControlwhileThe while loop repeats a group of statements an indefinite number of timesunder control of a logical condition.

A matching end delineates the statements.Here is a complete program, illustrating while, if, else, and end, that usesinterval bisection to find a zero of a polynomial.a = 0; fa = -Inf;b = 3; fb = Inf;while b-a > eps*bx = (a+b)/2;fx = x^3-2*x-5;if sign(fx) == sign(fa)a = x; fa = fx;elseb = x; fb = fx;endendxThe result is a root of the polynomial x3 - 2x - 5, namelyx =2.09455148154233The cautions involving matrix comparisons that are discussed in the section onthe if statement also apply to the while statement.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)5-55Programming with MATLABline = fgetl(fid);if isempty(line) | strncmp(line,'%',1)continueendcount = count + 1;enddisp(sprintf('%d lines',count));breakThe break statement lets you exit early from a for or while loop. In nestedloops, break exits from the innermost loop only.Here is an improvement on the example from the previous section. Why is thisuse of break a good idea?a = 0; fa = -Inf;b = 3; fb = Inf;while b-a > eps*bx = (a+b)/2;fx = x^3-2*x-5;if fx == 0breakelseif sign(fx) == sign(fa)a = x; fa = fx;elseb = x; fb = fx;endendx5-6Other Data StructuresOther Data StructuresThis section introduces you to some other data structures in MATLAB,including:• Multidimensional arrays• Cell arrays• Characters and text• StructuresMultidimensional ArraysMultidimensional arrays in MATLAB are arrays with more than twosubscripts.

They can be created by calling zeros, ones, rand, or randn withmore than two arguments. For example,R = randn(3,4,5);creates a 3-by-4-by-5 array with a total of 3x4x5 = 60 normally distributedrandom elements.A three-dimensional array might represent three-dimensional physical data,say the temperature in a room, sampled on a rectangular grid. Or, it mightrepresent a sequence of matrices, A(k), or samples of a time-dependent matrix,A(t). In these latter cases, the (i, j)th element of the kth matrix, or the tkthmatrix, is denoted by A(i,j,k).MATLAB’s and Dürer’s versions of the magic square of order 4 differ by aninterchange of two columns. Many different magic squares can be generated byinterchanging columns.

The statementp = perms(1:4);generates the 4! = 24 permutations of 1:4. The kth permutation is the rowvector, p(k,:). ThenA = magic(4);M = zeros(4,4,24);for k = 1:24M(:,:,k) = A(:,p(k,:));end5-75Programming with MATLABstores the sequence of 24 magic squares in a three-dimensional array, M. Thesize of M issize(M)ans =4424...16321316281113103812831211016117131478141210612156191026111574141516513162385111012976141415151It turns out that the third matrix in the sequence is Dürer’s.M(:,:,3)ans =16594310615211714138121The statementsum(M,d)computes sums by varying the dth subscript.

Sosum(M,1)is a 1-by-4-by-24 array containing 24 copies of the row vector345-8343434Other Data Structuresandsum(M,2)is a 4-by-1-by-24 array containing 24 copies of the column vector34343434Finally,S = sum(M,3)adds the 24 matrices in the sequence. The result has size 4-by-4-by-1, so it lookslike a 4-by-4 array.S =204204204204204204204204204204204204204204204204Cell ArraysCell arrays in MATLAB are multidimensional arrays whose elements arecopies of other arrays.

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

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

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

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