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

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

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

Thesecond call to fprintf outputs the table of numbers. The format control stringspecifies the format for each line of the table:• A fixed-point value of six characters with two decimal places• Two spaces• A fixed-point value of twelve characters with eight decimal placesfprintf converts the elements of array y in column order. The function usesthe format string repeatedly until it converts all the array elements.Now use fscanf to read the exponential data file.fid = fopen('exptable.txt','r');title = fgetl(fid);[table,count] = fscanf(fid,'%f %f',[2 11]);6-616Importing and Exporting Datatable = table';status = fclose(fid);The second line reads the file title. The third line reads the table of values, twofloating-point values on each line until it reaches end of file.

count returns thenumber of values matched.A function related to fprintf, sprintf, outputs its results to a string insteadof a file or the screen. For example,root2 = sprintf('The square root of %f is %10.8e.\n',2,sqrt(2));Closing a FileWhen you finish reading or writing, use fclose to close the file. For example,this line closes the file associated with file identifier fid.status = fclose(fid);This line closes all open files.status = fclose('all');Both forms return 0 if the file or files were successfully closed or -1 if theattempt was unsuccessful.MATLAB automatically closes all open files when you exit from MATLAB. It isstill good practice, however, to close a file explicitly with fclose when you arefinished using it.

Not doing so can unnecessarily drain system resources.Note Closing a file does not clear the file identifier variable fid. However,subsequent attempts to access a file through this file identifier variable willnot work.6-627Editing and DebuggingM-FilesStarting the Editor/Debugger . . . . .

. .Creating a New M-File in the Editor/Debugger .Opening Existing M-Files in the Editor/DebuggerOpening the Editor Without Starting MATLAB .Closing the Editor/Debugger . . . . . . . . ..........................7-37-47-57-67-6Creating and Editing M-Files with the Editor/Debugger 7-8Appearance of an M-File . . . . . .

. . . . . . . . . . 7-8Navigating in an M-File . . . . . . . . . . . . . . . . 7-11Saving M-Files . . . . . . . . . . . . . . . . . . . 7-15Running M-Files from the Editor/Debugger . . . . . . . . 7-15Printing an M-File . . . . . . . . . . . . . . . . . . 7-16Closing M-Files . . . . . . . . .

. . . . . . . . . . 7-16Debugging M-Files . . . . . . . . .Types of Errors . . . . . . . . . . .Finding Errors . . . . . . . . . . . .Debugging Example – The Collatz ProblemUsing Debugging Features . . . . . . ..................................... 7-17. 7-17. 7-17. 7-18. 7-22Preferences for the Editor/Debugger . . . . . . . . .General Preferences for the Editor/Debugger . . .

. . . .Font & Colors Preferences for the Editor/Debugger . . . . .Display Preferences for the Editor/Debugger . . . . . . .Keyboard and Indenting Preferences for the Editor/DebuggerPrinting Preferences for the Editor/Debugger . . . . . . .7-357-367-377-387-407-427Editing and Debugging M-FilesThere are several methods for creating, editing, and debugging M-files, whichare files containing MATLAB code.TaskOptionInstructionsCreatingand EditingM-filesMATLAB Editor“Starting the Editor/Debugger”on page 7-3MATLAB Editor instand-alone mode(without runningMATLAB)“Opening the Editor WithoutStarting MATLAB” on page 7-6Any text editor, such asEmacs or viSpecify the other editor as thedefault using preferences – see“Editor” on page 7-36General debugging tips“Types of Errors” and “FindingErrors” on page 7-17MATLAB Debugger“Using Debugging Features” onpage 7-22MATLAB debuggingfunctions“Using Debugging Features” onpage 7-22DebuggingM-filesUse preferences to set up the editing and debugging environment to best meetyour needs.To learn more about writing M-files, see “Programming and Data Types”.7-2Starting the Editor/DebuggerStarting the Editor/DebuggerThe MATLAB Editor/Debugger provides a graphical user interface for basictext editing features for any file type, as well as for M-file debugging.

TheEditor/Debugger is a single tool that you can use for editing, debugging, orboth. There are various ways to start the Editor/Debugger – see the sections:• “Creating a New M-File in the Editor/Debugger” on page 7-4• “Opening Existing M-Files in the Editor/Debugger” on page 7-5• “Opening the Editor Without Starting MATLAB” on page 7-6 (no Debugger)After starting the Editor/Debugger, follow the instructions for:• “Creating and Editing M-Files with the Editor/Debugger” on page 7-8• “Debugging M-Files” on page 7-17• “Closing the Editor/Debugger” on page 7-6Following is an illustration of the Editor/Debugger opened to an existing M-file.If the Editor/Debugger window is not wide enough, the toolbar buttons on theright will be not be shown. The menu will wrap, and all toolbar functions are7-37Editing and Debugging M-Filesavailable from equivalent menu items.

To see all toolbar buttons, make theEditor/Debugger window wider.To dock the Editor/Debugger inside the MATLAB desktop, select Dock M-Filefrom the View menu.To change the default appearance and behavior of the Editor/Debugger, followthe instructions in “Preferences for the Editor/Debugger” on page 7-35.Creating a New M-File in the Editor/DebuggerTo create a new M-file in the Editor/Debugger, either click the new file buttonon the MATLAB toolbar, or select File -> New -> M-file from the MATLABdesktop.

You can also create a new M-file using the context menu in theCurrent Directory browser – see “Creating New Files” on page 5-24. TheEditor/Debugger opens, if it is not already open, with a blank file in which youcan create an M-file.If the Editor/Debugger is open, create more new files by using the new filebuttonon the toolbar, or select File -> New -> M-file.Function EquivalentType edit in the Command Window to create a new M-file in the Editor/Debugger.If you type edit filename.m and filename.m does not yet exist, a promptappears asking if you want to create a new file titled filename.m.• If you click Yes, the Editor/Debugger creates a blank file titled filename.m.If you do not want the dialog to appear in this situation, either check that boxin the dialog or specify it in preferences for “Prompt” on page 7-40. In thatcase, the next time you type edit filename.m, the file will be createdwithout first prompting you.• If you click No, the Editor/Debugger does not create a new file.

If you do notwant the dialog to appear in this situation, either check that box in the dialogor specify it in preferences for “Prompt” on page 7-40. In that case, the nexttime you type edit filename.m, a “file not found” error will appear.7-4Starting the Editor/DebuggerOpening Existing M-Files in the Editor/DebuggerTo open an existing M-file in the Editor/Debugger, click the open buttononthe MATLAB or Editor/Debugger toolbar, or select File -> Open.

Then, fromthe Open dialog box, select the M-file and click Open. You can also open filesfrom the Current Directory browser – see “Opening Files” on page 5-26.You can select a file to open from the most recently used files, which are listedat the bottom of the File menu in the desktop as well as in the Editor/Debugger.You can change the number of files appearing on the list – see “Preferences forthe Editor/Debugger” on page 7-35.If the Editor/Debugger is not already open, it opens with the file displayed. Ifit is already open, the file appears either in its own window or as a tab in thecurrent window as specified in “Opening files in editor” on page 7-38.

To makea document in the Editor/Debugger become the current document, click on it oruse the Window menu or tabs.You can set a preference that instructs MATLAB on startup to automaticallyopen the files that were open when the previous MATLAB session ended. Forinstructions, see the On restart preference in “General Preferences for theEditor/Debugger” on page 7-36.Function EquivalentUse the edit or open function to open an existing M-file in the Editor/Debugger. For example, typeedit collatz.mto open the file collatz.m in the Editor/Debugger.Opening a SelectionWithin a file in the Editor/Debugger, select a function, right-click, and selectOpen Selection from the context menu.

The file opens in the Editor/Debugger.Getting Help for a FunctionWithin a file in the Editor/Debugger, select a function, right-click, and selectHelp on Selection from the context menu. The reference page for that functionopens in the Editor/Debugger, or if the reference page does not exist, the M-filehelp is shown instead.7-57Editing and Debugging M-FilesAccessing Your Source Control SystemIf you use a source control system for M-files, you can access it from within theEditor/Debugger to check out files. See Chapter 9, “Interfacing with SourceControl Systems.”Opening the Editor Without Starting MATLABOn Windows platforms, you can use the MATLAB Editor without startingMATLAB. To do so, double-click an M-file in Windows Explorer.

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

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

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

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