Using MATLAB (779505), страница 30
Текст из файла (страница 30)
Click a tab to see that results list as well asthe search criteria.Finding the Next or Previous Occurrence of the String. To find the next occurrence ofthe string you entered in the Find & Replace dialog box, select Find Next fromthe Edit menu. To find the previous occurrence of that string (find backwards),press Shift+F3.Function Equivalent. Use lookfor to search for the specified string in the first lineof help in all M-files on the search path.Replacing a String. After searching for a string within files, you can replace thespecified content in the current file.1 Open the file in the Editor if it’s not already open. You can open it from theFind & Replace dialog box – see step 4 in “Finding a String” on page 7-12.Be sure that the file in which you want to replace the string is the currentfile in the Editor.2 Be sure the Look in field in the Find & Replace dialog box shows the nameof the file in which you want to replace the string. The Replace button in theFind & Replace dialog box becomes selectable.3 In the Replace with field, type the text that is to replace the specified string.4 Click Replace to replace the string in the selected line, or click Replace Allto replace all instances in the currently open file.The text is replaced.7-14Creating and Editing M-Files with the Editor/Debugger5 To save the changes, select Save from the File menu.You can repeat this for multiple files.Saving M-FilesAfter making changes to an M-file, you will see an asterisk (*) next to the filename in the title bar of the Editor/Debugger.
This indicates there are unsavedchanges to the file.To save the changes, use one of the Save commands in the File menu:• Save – Saves the file to its existing name. If the file was newly created, theSave file as dialog box opens, where you assign a name to the file and saveit. Another way to save is by using the save buttonon the toolbar.• Save As – The Save file as dialog box opens, where you assign a name to thefile and save it. You do not need to type the .m extension because MATLABautomatically assigns the .m extension to the filename.
If you do not want anextension, type a . (period) after the filename.• Save All – Saves all named files to their existing filenames. For all newlycreated files, the Save file as dialog box opens, where you assign a name toeach file and save it.Running M-Files from the Editor/DebuggerYou can run a script, that is, an M-file that doesn’t require an input argument,directory from the Editor/Debugger by clicking the run buttonon thetoolbar, or by selecting Run from the Debug menu.If the file is not in a directory on the search path or in the current directory, adialog box appears presenting you with options that allow you to run the file.You can either change the current directory to the directory containing the file,or you can add to the search path the directory containing the file.Note that if the file has unsaved changes, running it from the Editor/Debuggerautomatically saves the changes before running. In that event, the menu itembecomes Save and Run.See “Running an M-File with Breakpoints” on page 7-24 for additionalinformation about running M-files while debugging.7-157Editing 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 in files.
See Chapter 9, “Interfacing with SourceControl Systems.”Printing an M-FileTo print an entire M-file, select Print from the File menu, or click the printbuttonon the toolbar. To print the current selection, select Print Selectionfrom the File menu. Complete the standard print dialog box that appears.See also “Printing Preferences for the Editor/Debugger” on page 7-42 to specifya different font for printing, color or black and white printing, and otheroptions.Closing M-FilesTo close the current M-file, select Close filename from the File menu.
If thereare multiple files open in a single Editor/Debugger window, click the close boxin the Editor toolbar to close the current M-file. This is different from the closebox in the titlebar of the Editor/Debugger, which closes the Editor/Debugger,including all open files.Close box for Editor/DebuggerClose box for current fileIf each file is open in a separate Editor/Debugger window, close all of the filesat once using the Close All item in the Window menu.When you close the current file and it is the only file open, then the Editor/Debugger closes as well.When you close a file which has unsaved changes, you are prompted to save thefile.7-16Debugging M-FilesDebugging M-FilesThis section introduces general techniques for finding errors, and thenillustrates MATLAB debugger features found in the Editor/Debugger anddebugging functions using a simple example.
It includes these topics:• “Types of Errors” on page 7-17• “Finding Errors” on page 7-17• “Debugging Example – The Collatz Problem” on page 7-18• “Trial Run for Example” on page 7-20• “Using Debugging Features” on page 7-22Types of ErrorsDebugging is the process by which you isolate and fix problems with your code.Debugging helps to correct two kinds of errors:• Syntax errors – For example, misspelling a function name or omitting aparenthesis.
“Syntax Highlighting” on page 7-8 helps you identify theseproblems. MATLAB detects most syntax errors and displays an errormessage in the Command Window describing the error and showing its linenumber in the M-file. Position the cursor over the error message and pressCtrl+Enter to open the M-file at that line. Use the pcode function to checkfor syntax errors in your M-file without running the M-file.• Run-time errors – These errors are usually algorithmic in nature.
Forexample, you might modify the wrong variable or perform a calculationincorrectly. Run-time errors are apparent when an M-file producesunexpected results.Finding ErrorsUsually, it’s easy to find syntax errors based on MATLAB’s error messages.Run-time errors are more difficult to track down because the function’s localworkspace is lost when the error forces a return to the MATLAB baseworkspace. Use the following techniques to isolate the cause of run-time errors:• Remove selected semicolons from the statements in your M-file.
Semicolonssuppress the display of intermediate calculations in the M-file. By removing7-177Editing and Debugging M-Filesthe semicolons, you instruct MATLAB to display these results on your screenas the M-file executes.• Add keyboard statements to the M-file. Keyboard statements stop M-fileexecution at the point where they appear and allow you to examine andchange the function’s local workspace. This mode is indicated by a specialprompt, “K>>.” Resume function execution by typing return and pressing theReturn key.• Comment out the leading function declaration and run the M-file as a script.This makes the intermediate results accessible in the base workspace.• Use the depfun function to see the dependent functions.• Use the MATLAB Editor/Debugger or debugging functions.
They are usefulfor correcting run-time errors because you can access function workspacesand examine or change the values they contain. You can set and clearbreakpoints, lines in an M-file at which execution halts. You can changeworkspace contexts, view the function call stack, and execute the lines in anM-file one by one.The remainder of this section on debugging M-files describes the use of theEditor/Debugger and debugging function using an example.Debugging Example – The Collatz ProblemThe example debugging session requires you to create two M-files, collatz.mand collatzplot.m, that produce data for the Collatz problem. For any givenpositive integer, n, the Collatz function produces a sequence of numbers thatalways resolves to 1. If n is even, divide it by 2 to get the next integer in thesequence.
If n is odd, multiply it by 3 and add 1 to get the next integer in thesequence. Repeat the steps for the next integer in the sequence until the nextinteger is 1. The number of integers in the sequence varies, depending on thestarting value, n.The Collatz problem is to prove that the Collatz function will resolve to 1 for allpositive integers. The M-files for this example are useful for studying theproblem. The file collatz.m generates the sequence of integers for any givenn.
The file collatzplot.m calculates the number of integers in the sequence forany given n and plots the results. The plot shows patterns that can be furtherstudied.7-18Debugging M-FilesFollowing are the results when n is 1, 2, or 3.nSequenceNumber of Integers in the Sequence11122 1233 10 5 16 8 4 2 18M-Files for the Collatz ProblemFollowing are the two M-files you use for the debugging example. To createthese files on your system, open two new M-files. Select and copy the followingcode from the Help browser and paste it into the M-files. Save and name thefiles collatz.m and collatzplot.m.
Be sure to save them to your currentdirectory or add to the search path the directory where you save them. One ofthe files has an embedded error for purposes of illustrating the debuggingfeatures.Code for collatz.m.function sequence=collatz(n)% Collatz problem. Generate a sequence of integers resolving to 1% For any positive integer, n:% Divide n by 2 if n is even% Multiply n by 3 and add 1 if n is odd% Repeat for the result% Continue until the result is 1%sequence = n;next_value = n;while next_value > 1if rem(next_value,2)==0next_value = next_value/2;elsenext_value = 3*next_value+1;endsequence = [sequence, next_value];end7-197Editing and Debugging M-FilesCode for collatzplot.m.function collatzplot(n)% Plot length of sequence for Collatz problem% Prepare figureclfset(gcf,'DoubleBuffer','on')set(gca,'XScale','linear')%% Determine and plot sequence and seqeuence lengthfor m = 1:nplot_seq = collatz(m);seq_length(m) = length(plot_seq);line(m,plot_seq,'Marker','.','MarkerSize',9,'Color','blue')drawnowendTrial Run for ExampleTry out collatzplot to see if it works correctly.
















