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

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

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

Use a simple input value, forexample, 3, and compare the results to those shown in the preceding table.Typingcollatzplot(3)produces the plot shown in the following figure.7-20Debugging M-FilesThe plot for 1 appears to be correct – when n = 1, the Collatz series is 1, andcontains one integer. But for n = 2 and n = 3 it is wrong because there shouldbe only one value plotted for each integer, the length of the sequences, whichthe preceding table shows to be 2 and 8 respectively. Instead, multiple valuesare plotted. Use MATLAB debugging features to isolate the problem.7-217Editing and Debugging M-FilesUsing Debugging FeaturesYou can debug the M-files using the Editor/Debugger and debugging functions.You can use both methods interchangeably.

The example describes bothmethods.The debugging process consists of:• “Preparing for Debugging” on page 7-22• “Setting Breakpoints” on page 7-22• “Running an M-File with Breakpoints” on page 7-24• “Stepping Through an M-File” on page 7-25• “Examining Values” on page 7-26• “Correcting Problems and Ending Debugging” on page 7-29Preparing for DebuggingDo the following to prepare for debugging:• Open the file – To use the Editor/Debugger for debugging, open it with thefile you will run, in this example, collatzplot.m.• Save changes – If you are editing the file, save the changes before you begindebugging. If you try to run and debug a file with unsaved changes, the fileis automatically saved before it runs.• Add the file(s) to a directory on the search path or be sure it is in the currentdirectory – Be sure the file you run and any files it calls are in directories thatare on the search path.

If all files to be used are in the same directory, youcan instead make that directory be the current directory.Setting BreakpointsSet breakpoints to pause execution of the function so you can examine valueswhere you think the problem might be. You can only set breakpoints atexecutable lines in saved files that are in the current directory or in directorieson the search path. When you create a new M-file, save it before settingbreakpoints.

You cannot set breakpoints while MATLAB is busy, for example,running an M-file.Breakpoints for the Example. It is unclear whether the problem in the example isin collatzplot or collatz. To start, set breakpoints in collatzplot.m at lines10, 11, and 12. The breakpoint at line 10 allows you to step into collatz to see7-22Debugging M-Filesif the problem might be there. The breakpoints at lines 11 and 12 stop theprogram where you can examine the interim results.Setting Breakpoints Using the Editor/Debugger. To set a breakpoint using the Editor/Debugger, click in the breakpoint alley at the line where you want to set thebreakpoint.

The breakpoint alley is the column to the right of the line number.You can set breakpoints only at lines that are preceded by a - (dash). Lines notpreceded by a dash, such as comments, are not executable. Other ways to set abreakpoint are to position the cursor in the line and then click the set/clearbreakpoint button on the toolbar, or select Set/Clear Breakpoint from theBreakpoints menu or the context menu.A breakpoint icon appears, as in the following illustration for line 10.Function Equivalent. To set a breakpoint using the debugging functions, usedbstop. For the example, typedbstop in collatzplot at 10dbstop in collatzplot at 11dbstop in collatzplot at 12Some useful related functions are:• dbtype – Lists the M-file with line numbers in the Command Window.• dbstatus – Lists breakpoints.Setting Stops for Conditions. Use the items on the Breakpoints menu or thedbstop function equivalents to instruct the program to stop when it encountersa problem.

For details, see dbstop.• Stop If Error, or dbstop if error• Stop If Warning, or dbstop if warning• Stop If NaN Or Inf (for not-a-number or infinite value), or dbstop if naninfor dbstop if infnan• Stop If All Error, or dbstop if all errorIf the File Is Not on the Search Path or In the Current Directory. When you add abreakpoint to a file that is not in a directory on the search path or in the currentdirectory, a dialog box appears presenting you with options that allow you to7-237Editing and Debugging M-Filesadd the breakpoint.

You can either change the current directory to thedirectory containing the file, or you can add to the search path the directorycontaining the file.Running an M-File with BreakpointsAfter setting breakpoints, run the M-file from the Command Window or theEditor/Debugger.For the example, run collatzplot for the simple input value, 3, by typing inthe Command Windowcollatzplot(3)The example, collatzplot, requires an input argument and therefore runsonly from the Command Window and not from the Editor/Debugger.Results of Running an M-File Containing Breakpoints. Running the M-file results inthe following:• The prompt in the Command Window changes to K>>, indicating thatMATLAB is in debug mode.• The program is paused at the first breakpoint, which in the example is line10.

This means that line 10 will be executed when you continue. The pauseis indicated in the Editor/Debugger by the green arrow just to the right of thebreakpoint as shown here.If you use debugging functions and have the Debugger options preference forCommand Window debugging checked, the line at which you are paused isdisplayed in the Command Window. For the example, it would show10plot_seq = collatz(m);• The function displayed in the Stack field on the toolbar changes to reflect thecurrent function. If you use debugging functions, use dbstack to view thecurrent call stack. The call stack includes subfunctions as well as calledfunctions.• If the file you’re running is not in the current directory or in a directory onthe search path, you’re prompted to either add the directory to the path orchange the current directory.7-24Debugging M-FilesStepping Through an M-FileWhile in debug mode, you can step through an M-file, pausing at points whereyou want examine values.Use the step buttons or the step items in the Debug menu of the Editor/Debugger, or use the equivalent functions.ToolbarButtonNoneDebugMenuItemDescriptionFunctionEquivalentContinueContinue execution of M-fileuntil completion or untilanother breakpoint isencountered.

The menu itemsays Run or Save and Run ifthe file is not running.dbcontGo UntilCursorContinue execution of M-fileuntil the line where the cursoris positioned. Also available onthe context menu.NoneStepExecute the current line of theM-file.dbstepStep InExecute the current line of theM-file and, if the line is a call toanother function, step into thatfunction.dbstep inStep OutAfter stepping in, runs the restof the called function orsubfunction, leaves the calledfunction, and pauses.dbstep outStepping In. In the example, collatzplot is paused at line 10.

Use the step-inbutton or type dbstep in in the Command Window to step into collatz andwalk through that M-file. Stepping in takes you to line 9 of collatz.7-257Editing and Debugging M-FilesThe pause indicator at line 10 of collatzplot changes to a hollow arrow ,indicating that MATLAB control is now in a function called from the mainprogram, which in the example is collatz.In the called function, you can do the same things you can do in the main(calling) function – set breakpoints, run, step through, and examine values.Stepping Out.

In the example, the program is paused at step 9 in collatz.Because the problem results are correct for n = 1, continue running theprogram since there is no need to examine values until n = 2. The fastest wayto run through collatz is to step out, which runs the rest of collatz andreturns to the next line in collatzplot, line 11. To step out, use the step-outbutton or type dbstep out in the Command Window.Examining ValuesWhile the program is paused, you can view the value of any variable currentlyin the workspace. Use the following methods to examine values:• “Where to Examine Values” on page 7-26• “Selecting the Workspace” on page 7-27• “Viewing Datatips in the Editor/Debugger” on page 7-27• “Viewing Values in the Command Window” on page 7-28• “Viewing Values in the Array Editor” on page 7-28• “Evaluating a Selection” on page 7-28Many of these methods are used in “Examining Values in the Example” onpage 7-28.Where to Examine Values.

When the program is paused, either at a breakpoint orat a line you have stepped to, you can examine values. Examine values whenyou want to see if a line of code has produced the expected result or not. If theresult is as expected, continue running or step to the next line. If the result isnot as expected, that line, or a previous line, contains an error.In the example, because the results for n = 1 are correct, there is no need toexamine values until n = 2. Therefore, continue or step through the firstiteration of the loop in collatzplot when m = 1. When collatzplot stops atline 10 the next time (when m = 2), step in to the collatz function so you canexamine values there.7-26Debugging M-FilesSelecting the Workspace. Variables assigned through the Command Window areconsidered to be the base workspace.

Variables created in each function havetheir own workspace. To examine a variable, you must first select itsworkspace. When you run a program, the current workspace is shown in theStack field. To examine values that are part of another function workspacecurrently running or the base workspace, first select that workspace from thelist in the Stack field.Viewing Datatips in the Editor/Debugger. In the Editor/Debugger, position thecursor to the left of a variable.

Its current value appears and stays in view untilyou move the cursor – this is called a datatip. In the example, position thecursor over n in collatz – the datatip shows that n = 2, as expected. Note thatthe Stack shows collatz as the current function.Hold the cursor overa variable to view itscurrent value.7-277Editing and Debugging M-FilesViewing Values in the Command Window. Type a variable name in the CommandWindow and MATLAB displays its current value.

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

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

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

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