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

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

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

To see the variablescurrently in the workspace, use who. To see the value of n for the example, typenand MATLAB returns the expected resultn =2Viewing Values in the Array Editor. You can view the value of any variable in theArray Editor. To view the current variables, open the Workspace browser. Inthe Workspace browser, double-click a variable – the Array Editor opens,displaying the value for that variable. You can also open the Array Editor for avariable using openvar.To see the value of n in the Array Editor for the example, typeopenvar nand the Array Editor opens, showing that n = 2 as expected.Evaluating a Selection.

Select a variable or equation in an M-file in the Editor/Debugger. Right-click and select Evaluate Selection from the context menu.MATLAB displays the value of the variable or equation in the CommandWindow. You cannot evaluate a selection while MATLAB is busy, for example,running an M-file.Examining Values in the Example. In collatz, use the step button or the functiondbstep. The program advances to line 10, where there is no need to examinevalues. Continue stepping until line 13.When you step again, the pause indicator jumps to line 17, just after the ifloop, as expected, given the code in line 13 for next_value = 2. When you step7-28Debugging M-Filesagain, you can check the value of sequence in line 17 and see that it is 2 1 asexpected for n = 2. Stepping again takes you from line 17 to line 10.

Becausenext_value is 1, the while loop ends. The pause indicator is at line 10 andappears as a green down arrow . This indicates that processing in the calledfunction is complete and program control will return to the calling program, inthis case, collatzplot line 10.In collatzplot, step again to advance to line 11, then line 12.

The variablesequence_length in line 11 is a vector with the elements 1 2, which is correct.Finally, step again to advance to line 13. Examining the values in line 12,m = 2 as expected, but the second variable, plot_seq, has two values, whereonly one value is expected. While plot_seq has the value expected, 2 1, it isthe incorrect variable for plotting. Instead, the variable seq_length should beplotted.Correcting Problems and Ending DebuggingThese are some of the ways to correct problems and end the debugging session:• “Changing Values and Checking Results” on page 7-29• “Ending Debugging” on page 7-30• “Clearing Breakpoints” on page 7-30• “Correcting an M-File” on page 7-31Many of these features are used in “Completing the Example” on page 7-31.Changing Values and Checking Results.

While debugging, you can change the valueof a variable in the current workspace to see if the new value produces expectedresults. While the program is paused, assign a new value to the variable in theCommand Window or in the Array Editor.

Then continue running or steppingthrough the program. If the new value does not produce the expected results,the program has a different or another problem.7-297Editing and Debugging M-FilesEnding Debugging. After identifying a problem, end the debugging session. Youmust end a debugging session if you want to change an M-file to correct aproblem or if you want to run other functions in MATLAB.Note Always quit debug mode before editing an M-file. If you edit an M-filewhile in debug mode, you can get unexpected results when you run the file.To end debugging, click the exit debug mode iconMode from the Debug menu., or select Exit DebugYou can instead use the function dbquit to end debugging.After quitting debugging, the pause indicators in the Editor/Debugger displayno longer appear, and the normal prompt >> now appears in the CommandWindow instead of the debugging prompt, K>>.

You can no longer access the callstack.Clearing Breakpoints. Breakpoints remain in a file until you clear them. Clear thebreakpoints if you want the program to run uninterrupted, such as afteridentifying and correcting a problem.To clear a breakpoint in the Editor/Debugger, click on the breakpoint icon fora line, or select Set/Clear Breakpoint from the Breakpoints or context menu.The breakpoint for that line is cleared.To clear all breakpoints in all files, select Clear All Breakpoints from theBreakpoints menu, or click theequivalent button on the toolbar.The function that clears breakpoints is dbclear. To clear all breakpoints, usedbclear all.

For the example, clear all of the breakpoints in collatzplot bytypingdbclear all in collatzplot7-30Debugging M-FilesBreakpoints are automatically cleared when you:• End the MATLAB session• Clear the M-file using clear name or clear all• Edit the file if the changes impact line numbering• Edit the file while in debug mode (although this does not always clearbreakpoints)Correcting an M-File.

To correct a problem in an M-file:1 Quit debugging.Do not make changes to an M-file while MATLAB is in debug mode. It couldproduce unexpected debugging results when you run the M-file.2 Clear all the breakpoints in the file.The breakpoints become unreliable once the M-file is edited. Thebreakpoints will produce unexpected debugging results when you run thefile.3 Make changes to the M-file.4 Save the M-file.5 Set breakpoints, if desired.6 Run the M-file again to be sure it produces the expected results.Completing the Example. To correct the problem in the example, do the following:1 End the debugging session. One way to do this is to select Exit Debug Modefrom the Debug menu.2 Clear the breakpoints in collatzplot.m.

One way to do this is by typingdbclear all in collatzplotin the Command Window.7-317Editing and Debugging M-Files3 In collatzplot.m line 12, change the string plot_seq to seq_length(m) andsave the file.4 Run collatzplot for n = 3 by typingcollatzplot(3)in the Command Window.5 Verify the result. The figure shows that the length of the Collatz series is 1when n = 1, 2 when n = 2, and 8 when n = 3, as expected.7-32Debugging M-Files6 Test the function for a slightly larger value of n, such as 6, to be sure theresults are still accurate. To make it easier to verify collatzplot for n = 6as well as the results for collatz, add this line at the end of collatz.msequencewhich displays the series in the Command Window.Then run collatzplot for n = 6 by typingcollatzplot(6)7-337Editing and Debugging M-Files7 To make debugging easier, you ran collatzplot for a small value of n.

Nowthat you know it works correctly, run collatzplot for a larger value toproduce more interesting results. Before doing so, you might want tosuppress output for the line you just added in step 6, line 18 of collatz.m,by adding a semicolon to the end of the line so it appears assequence;Then runcollatzplot(500)The following figure shows the lengths of the Collatz series for n = 1 throughn = 500.7-34Preferences for the Editor/DebuggerPreferences for the Editor/DebuggerUsing preferences, you can specify the default behavior for various aspects ofthe Editor/Debugger.To set preferences for the Editor/Debugger, select Preferences from the Filemenu in the Editor/Debugger.

The Preferences dialog box opens showingEditor/Debugger Preferences.7-357Editing and Debugging M-FilesYou can specify the following Editor/Debugger preferences:• “General Preferences for the Editor/Debugger” on page 7-36 (on the firstpanel, including the Editor preference)• “Font & Colors Preferences for the Editor/Debugger” on page 7-37• “Display Preferences for the Editor/Debugger” on page 7-38• “Keyboard and Indenting Preferences for the Editor/Debugger” on page 7-40• “Printing Preferences for the Editor/Debugger” on page 7-42General Preferences for the Editor/DebuggerWhen you first access preferences for the Editor/Debugger, you can specify thegeneral preferences described here.EditorBy default, the Built-in editor option is selected, meaning that MATLAB usesits own Editor/Debugger.To specify a text editor other than MATLAB’s Editor, such as Emacs or vi, tobe used when you open an M-file from within MATLAB, select Other.

In theOther field, type the path to the editor application you want to use.For example, specify C:\Applications\Emacs.exe in the Other field, and thenopen a file using Open from the File menu the MATLAB desktop. The fileopens in Emacs instead of in the MATLAB Editor/Debugger.Debugger optionsBy default, the item Automatically open files when debugging is checked.The result is that when you run an M-file containing breakpoints, theMATLAB Editor/Debugger opens when it encounters a breakpoint.If you use debugging functions, you might want to uncheck the item so that theEditor/Debugger does not open when a breakpoint is encountered.Most recently used file listUse this preference to specify the number of files that appear in the list of mostrecently used files in the File menu.7-36Preferences for the Editor/DebuggerOn restartTo start MATLAB and automatically open the files that were open when youlast shut down MATLAB, check the item Reopen files from previousMATLAB session.

If the item is unchecked and you close MATLAB when thereare files open in the Editor/Debugger, the next time you start MATLAB, theEditor/Debugger is not opened upon startup.Font & Colors Preferences for the Editor/DebuggerUse Font & Colors preferences to specify the font and colors used in files in theEditor/Debugger.FontEditor/Debugger font preferences specify the characteristics of the font used infiles in the Editor/Debugger. Select Use desktop font if you want the font inthe files to be the same as that specified under General - Font & Colors.

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

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

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

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