left-icon

MATLAB Succinctly®
by Dmitri Nesteruk

Previous
Chapter

of
A
A
A

CHAPTER 5

Working with Scripts

Working with Scripts


There are two ways of interacting with MATLAB. One is to simply type things into the Command Window—that way, you get to see the results immediately, but it becomes difficult (though not impossible) to write complicated programs. An alternative is to use scripts—separate files that make up your program. MATLAB scripts typically have the .m extension, and are plain-text files that MATLAB lets you edit, execute, and debug.

Script Templates

The simplest way to create a script in MATLAB is to click the New Script button (or the Ctrl+N shortcut). However, MATLAB also gives us a few script templates—ready-made script files representing certain constructs that we might want to create:

C:\Dropbox\Publications\Books\MATLAB Succintly\21.png

New object drop-down list.

It’s really only the top few options that we are interested in. In addition to creating a script, you can also create a Function, in which case you’ll simply get a stub for a function definition; you can make an Example, which is just a script file with nicely formatted documentation, ready for publication; next up is a Class, which is an OOP construct (see Chapter 7).

Other elements in this menu come from various toolboxes and aren’t necessarily script files.

So let’s use the Function template to create a reusable function for solving a quadratic equation:

function [x1,x2] = SolveQuadratic(a,b,c)
%SolveQuadratic Solves a quadratic equation

  disc = b*b - 4*a*c;

  x1 = (-b+sqrt(disc))/(2*a);

  x2 = (-b-sqrt(disc))/(2*a);

end

Let’s examine this function definition. First of all, immediately after the function keyword, we list all the values that the function is going to return, within square brackets (brackets are unnecessary if there’s only a single return value). In this case, these are the x1 and x2 values, which are solutions to the quadratic equation.

Then, after the = sign, we have the name of the function. Note that the file name should ideally match the function name, so the SolveQuadratic function should be saved in a script file called SolveQuadratic.m. The name of the function is followed by a set of function arguments in parentheses, separated by commas. When calling this function, the caller has to provide exactly as many arguments as are specified here (i.e. three).

The comment line right after the function declaration essentially provides documentation for whoever will be using this function. This is called the “H1 Line” in MATLAB. When we open the Function Browser for this function, what we’ll get is documentation generated from these comments:

C:\Dropbox\Publications\Books\MATLAB Succintly\22.png

Documentation for our SolveQuadratic function.

Now, after saving the .m file, we can start using the function, assuming that the file is available on MATLAB’s path:

>> SolveQuadratic(1,10,16)

ans =
    -2

Oops! That’s not quite right, is it? We were expecting two solutions but got just one (which happens in some quadratic equations, but still, we were expecting two values). The problem is that we invoked a function that returns two values, but didn’t specify storage for them, so MATLAB just took the first value and saved it in ans. Not very nice, is it? Well, the correct way to get both of the values is to assign them to variables like so:

>> [x,y] = SolveQuadratic(1,10,16)

x =
    -2

y =
    -8

That’s much better! This code line effectively declares both x and y on a single line, and, after the function call, both of the variables are ready to be used.

Sections

Before we start running scripts, we need to talk about script sections. These are important and serve two purposes:

  • Sections separate your script into several intelligible parts, making it nicer to read. In this regard, you can consider scripts as chapter or section headings of a book.
  • You can execute each section separately. This is great for testing out small parts of a large script.

A section is typically prefixed by %% (two percentage signs). As you prefix a section, you’ll notice that all the code until the next section is highlighted—this helps you figure out where the section ends.

To execute a section, you can press the Run Section button (or Ctrl+Enter). The section that gets executed is the one your cursor is currently in.

Running and Debugging

Running a script is simple—press the Run button (or F5), or use the Run Section option to just run part of the script. Of course, you can also run the script from the Command window, so assuming your file SolveQuadratic.m is on MATLAB’s path, you can just type SolveQuadratic, press Enter, and your script gets to execute.

While we assume most of our readers to be careful and proficient MATLAB users, errors sometimes do occur and it’s often worth checking up on the execution of the program. The first thing worth trying is Debugging—this is the process of being able to stop the program mid-stream and inspect the values of the variables.

Debugging is done using breakpoints—markers that indicate the location where execution should pause. The Breakpoints section on the Editor tab has several options related to breakpoints:

27

Breakpoint options.

Of most benefit is the Set/Clear option. This creates a breakpoint at the current line in your program. You can also set a breakpoint by pressing F12 or clicking on the margin on the left-hand side of the editor.

A triggered breakpoint.

One a breakpoint triggers, execution will stop and a green line will indicate the line at which the script was paused. You can then run the program line-by-line or continue execution. Variables can be expected either in the Workspace Window or, as shown above, by simply hovering the mouse over the symbol in the editor.

Profiling

We all get this moment when our program runs slowly for some unknown reason and we want to know why.

If your goal is to simply get a time measurement for a chunk of code, consider using the tic and toc functions, which start and stop a simple timer:

tic
% your code here
toc

As soon as you call toc, the timer stops and the elapsed time gets printed to the command window:

Elapsed time is 1.127136 seconds.

Note: Since tic and toc only start/stop measuring time when they are actually invoked, make sure that if you use the Command Window you call them both (and the code to profile in between) in a single statement. Otherwise, you’ll be measuring not just your own algorithm, but your typing speed, too!

If you’re after a more complete, comprehensive report on the performance of your script, you need to profile your script. MATLAB has a built-in profiler that you can use to determine which part of your script took the most time—this lets you fine-tune the bottlenecks in your scripts and thus improve their overall performance. You can start profiling with the Run and Time button—when you press it and execute your script, MATLAB will pop up an additional window containing some metrics of your script’s performance:

29

Profile summary.

The profiling summary shown in Figure 15 gives an indication of the number of times a function was invoked and how much time it took together with all the things it called, as well as the amount of time that the function itself spent doing something. It is possible to click each of the functions to get detailed information about the particular lines and how much time they took.

Of course, you can also invoke the profiler from the Command Window:

>> profile on
>> myscript
>> profile off
>> profile viewer

Publishing

Imagine you are working on a complicated algorithm and your manager suddenly wants a status update on your work. With MATLAB’s Publishing feature, what you can do is click a single button, and your script, together with all the plots and calculations it made, gets packaged as a document ready to be sent off.

It is possible to publish MATLAB scripts into various types of documents, including HTML, LaTeX, PDF, and others. If you want to publish your script to a document, click the Publish tab, choose Publish, Settings and choose the format and other options you need:

26

A note on LaTeX

Script file publishing formats.

Now, regardless of the output format you choose, it’s important to realize what actually happens with your code as it gets published. Here are the key processes that take place:

  • All section headings become top-level headings with the exception of the first one. The first section you create becomes the title heading of the whole document.
  • Comments immediately after the section heading turn into paragraphs of text. Note that MATLAB supports additional formatting in such comments, such as options for making text bold or italic, making hyperlinks, or even including LaTeX formulae.
  • Any executable code that you have gets placed into the document. MATLAB applies some syntax highlighting so the code looks nice.
  • All code you wrote gets executed. Output error/warning messages also end up in the published output.
  • Any images you generate also get included in the document.

To generate a document, simply press Publish—it really is that simple.

Comparison and Search

The ability to search for a particular file is built into all operating systems, but MATLAB also has its own facilities for searching either for a particular file name or for files containing specific text. The Home ribbon tab has a Find Files button that lets you do exactly this:

C:\Dropbox\Publications\Books\MATLAB Succintly\23.png

The Find Files window.

Just below that button is the Compare button, which lets you compare two files—handy for seeing changes as you update your code:

C:\Dropbox\Publications\Books\MATLAB Succintly\24.png

The File Comparison window. Added lines are shown in green, changed lines in red.

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.