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

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

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

Use the Cut, Copy, Paste, Undo, and Redo features fromthe Edit menu when working in the Command Window. Some of these featuresare also available in the context menu for the Command Window.Recalling Previous Lines. Use the arrow, tab, and control keys on your keyboard torecall, edit, and reuse functions you typed earlier.

For example, suppose youmistakenly enterrho = (1+ sqt(5))/2MATLAB responds withUndefined function or variable 'sqt'.because you misspelled sqrt. Instead of retyping the entire line, press thekey. The previously typed line is redisplayed. Use the left arrow key to movethe cursor and add the missing r. Repeated use of the up arrow key recallsearlier lines.The functions you enter are stored in a buffer.

You can use smart recall to recalla previous function whose first few characters you specify. For example, typingthe letters plo and pressing the up arrow key recalls the last function thatstarted with plo, as in the most recent plot function. This feature is casesensitive.3-73Running MATLAB FunctionsFollowing is the complete list of arrow and control keys you can use in theCommand Window. Many of these keys should be familiar to users of theEmacs editor.KeyControlKeyOperationCtrl+PRecall previous line. See also “CommandHistory” on page 3-17, which is a log ofpreviously used functions, and “Keeping aSession Log” on page 3-12.Ctrl+NRecall next line.Ctrl+BMove back one character.Ctrl+FMove forward one character.Ctrl+Ctrl+RMove right one word.Ctrl+Ctrl+LMove left one word.HomeCtrl+AMove to beginning of line.EndCtrl+EMove to end of line.EscCtrl+UClear line.DeleteCtrl+DDelete character at cursor.BackspaceCtrl+HDelete character before cursor.Ctrl+KDelete (kill) to end of line.Shift+HomeHighlight to beginning of line.Shift+EndHighlight to end of line.Tab Completion.

MATLAB completes the name of a function, variable, filename,or handle graphics property if you type the first few letters and then press theTab key. If there is a unique name, the name is automatically completed. Forexample, if you created a variable costs_march, typecosts3-8The Command Windowand press Tab. MATLAB completes the name, displayingcosts_marchPress Return or Enter to run the statement. In this example, MATLABdisplays the contents of costs_march.If there is more than one name that starts with the letters you typed, press theTab key again to see a list of the possibilities. For example, typecosand press Tab.

MATLAB does not display anything, indicating there aremultiple names beginning with cos. Press Tab again and MATLAB displayscoscos_trcoshcosintcostfuncosts_marchThe resulting list of possibilities includes the variable name you created,costs_march, but also includes functions that begin with cos.Note that the list might include files which are not valid commands, includingprivate functions.Clearing the Command WindowSelect Clear Command Window from the Edit menu to clear it. This does notclear the workspace, but only clears the view.

Afterwards, you still can use theup arrow key to recall previous functions.Function Equivalent. Use clc to clear the Command Window. Similar to clc, thehome function moves the prompt to the top of the Command Window.Suppressing OutputIf you end a line with a semicolon ( ; ), MATLAB runs the statement but doesnot display any output when you press the Enter or Return key. This isparticularly useful when you generate large matrices. For example, typingA = magic(100);and then pressing Enter or Return creates A but does not display the resultingmatrix.3-93Running MATLAB FunctionsPaging of Output in the Command WindowIf output in the Command Window is lengthy, it might not fit within the screenand will display too quickly for you to see it. Use the more function to controlthe paging of output in the Command Window.

By default, more is off. Whenyou type more on, MATLAB displays only a page (a screen full) of output at atime. After the first screen displays, press one of the following keys.KeyActionEnter or ReturnTo advance to the next lineSpace BarTo advance to the next pageqTo stop displaying the outputControlling the Format and Spacing of Numeric OutputBy default, numeric output in the Command Windows is displayed as 5-digitscaled, fixed-point values. Use the text display preference to change thenumeric format of output. The text display format affects only how numbersare shown, not how MATLAB computes or saves them.Function Equivalent.

Use the format function to control the output format of thenumeric values displayed in the Command Window. The format you specifyapplies only to the current session. More advanced alternatives are listed in the“See Also” section of the format reference page.Examples of Formats. Here are a few examples of the various formats and theoutput produced from the following two-element vector x, with components ofdifferent magnitudes.x = [4/3 1.2345e–6]format short e1.3333e+0001.2345e–006format short1.33330.0000format +++3-10The Command WindowFor a complete list and description of available formats, see the reference pagefor format. If you want more control over the output format, use the sprintfand fprintf functions.Controlling Spacing. Use the text display preference or format function to controlspacing in the output. Useformat compactto suppress blank lines, allowing you to view more information in theCommand Window. To include the blank lines, which can help make outputmore readable, useformat loosePrinting Command Window ContentsTo print the complete contents of the Command Window, select Print from theFile menu.

To print only a selection, first make the selection in the CommandWindow and then choose Print Selection from the File menu.Running ProgramsRunning M-FilesRun M-files, files that contain code in the MATLAB language, the same waythat you would run any other MATLAB function. Type the name of the M-filein the Command Window and press Enter or Return.To display each function in the M-file as it executes, use the Display preferenceand check Echo on, or use the echo function set to on.Interrupting a Running ProgramYou can interrupt a running program by pressing Ctrl+C or Ctrl+Break at anytime.On Windows platforms, you may have to wait until an executing built-infunction or MEX-file has finished its operation. On UNIX systems, programexecution will terminate immediately.3-113Running MATLAB FunctionsRunning External ProgramsThe exclamation point character, !, is a shell escape and indicates that the restof the input line is a command to the operating system.

Use it to invoke utilitiesor run other programs without quitting from MATLAB. On UNIX, for example,!vi darwin.minvokes the vi editor for a file named darwin.m. After the program completes oryou quit the program, the operating system returns control to MATLAB. Seethe functions unix and dos to run external programs that return results andstatus.Opening M-FilesTo open an M-file, select the file or function name in the Command Window,and then right-click and select Open Selection from the context window. TheM-file opens in the Editor/Debugger.Examining ErrorsIf an error message appears when running an M-file, click on the underlinedportion of the error message, or press Ctrl+Enter.

The offending M-file opensin the Editor, scrolled to the line containing the error.Keeping a Session LogThe diary FunctionThe diary function creates a copy of your MATLAB session in a disk file,including keyboard input and system responses, but excluding graphics. Youcan view and edit the resulting text file using any word processor. To create afile on your disk called sept23.out that contains all the functions you enter, aswell as MATLAB’s output, enterdiary('sept23.out')To stop recording the session, usediary('off')3-12The Command WindowOther Session LogsThere are two other means of seeing session information:• The Command History, which contains a log of all functions executed in thecurrent and previous sessions• For Windows platforms, the logfile startup option – see “Adding StartupOptions for Windows Platforms” on page 1-5Preferences for the Command WindowUsing preferences, you can specify the format for how numeric values aredisplayed, set echoing on automatically for each session, specify the font type,style, and size, and set the colors used for syntax highlighting for contents ofthe Command Window.To set preferences for the Command Window, select Preferences from the Filemenu in the Command Window.

The Preferences dialog box opens showingCommand Window Preferences.3-133Running MATLAB FunctionsText Display and Display Preferences for the Command WindowText display. Specify how output appears in the Command Window:• Numeric format – Output format of numeric values displayed in theCommand Window. This affects only how numbers are displayed, not howMATLAB computes or saves them. The format reference page includes thelist of available formats.• Numeric display – Spacing of output in the Command Window. To suppressblank lines, use compact. To display blank lines, use loose. For moreinformation, see the reference page for format.• Spaces per tab – Number of spaces assigned to a tab stop when displayingoutput.

The default is 4.3-14The Command WindowDisplay. Specify echoing option and buffer size:• Echo on – Check the box if you want commands running in M-files to displayin the Command Window during the M-file execution. For more information,see the reference page for echo.• Wrap lines – Input and output in the Command Window uses multiple linesto fit within the current width of the Command Window.

Note that thehorizontal scroll bar does not appear in this mode because it is not needed.• Limit matrix display width to eighty columns – Check the box if you wantMATLAB to display only 80 columns of matrix output, regardless of thewidth of the Command Window. Uncheck the box if you make the CommandWindow wider than 80 columns and want matrix output to fill the width ofthe Command Window. See also the display reference page.• Enable up to n tab completions – Check the box if you want to use tabcompletion when typing functions in the Command Window. Then enter alimit in the edit box.

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

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

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

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