Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 45 ยท Getting Started

Variables, Output and Help

Create variables, follow the naming rules, print with disp and fprintf, control number display with format, and find answers with help, doc and lookfor.

Every program does three basic things: it stores values, shows results and, when you get stuck, lets you look something up. In MATLAB and Octave the first two are one-liners. Assignment creates a variable the moment you use it, disp and fprintf print what you want, and a built-in help system answers most questions about functions without opening a browser.

This lesson covers all of that. The real commands are shown as read-only MATLAB/Octave blocks (they behave the same in both), and a Python stand-in lets you play with number formatting and naming rules right here. If you have not seen the command window yet, read The Desktop, Command Window and Scripts first.

Creating variables

Assignment uses a single =. You never declare a type; the variable is created on first use and its type comes from the value.

MATLAB
age = 31;
price = 19.99;
name = 'Ada';
is_ready = true;

Numbers are stored as double (64-bit floating point) unless you ask for something else. You can reassign a variable to a value of a different kind at any time. A variable that you assign inside one command can be used in the next:

MATLAB
width = 4;
height = 2.5;
area = width * height     % prints: area = 10

Naming rules

A variable name:

  • must start with a letter,
  • can then contain letters, digits and underscores,
  • is case sensitive (total, Total and TOTAL are three different variables),
  • cannot be a keyword such as if, for, end or function.

Names like speed_2, maxValue and x1 are fine. 2fast, my-var and end are not. MATLAB limits names to 63 characters, which namelengthmax reports.

Warning: Nothing stops you from naming a variable sum, max or length. It will work until you try to call the real function and MATLAB tries to index your variable instead. Choose names like total or longest. A later lesson, Common Mistakes and How to Fix Them, shows what this bug looks like.

You can check a name with isvarname('my-var'), which returns 0 (false) here, and list reserved words with iskeyword.

The stand-in below applies the same rules in Python so you can test names of your own. It is a rough check, not a replacement for isvarname.

Python Is this a valid variable name? (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Printing results

There are three ways to see a value.

Leave off the semicolon. The name and value are printed together:

MATLAB
>> speed = 12.5
speed =

   12.5000

disp prints just the value, with no name and no x = line:

MATLAB
>> disp(speed)
   12.5000
>> disp('Done')
Done

disp is good for short messages and for showing a whole matrix cleanly.

fprintf prints formatted text, like printf in C. You write a template with placeholders and give the values to fill in:

MATLAB
>> fprintf('Speed is %.1f m/s\n', speed)
Speed is 12.5 m/s
>> fprintf('%d apples and %d pears\n', 3, 4)
3 apples and 4 pears

Common placeholders:

Placeholder Meaning
%d integer
%f fixed-point number (%.2f gives two decimals)
%e scientific notation
%g the shorter of %f and %e
%s text
%% a literal percent sign

Unlike disp, fprintf does not add a newline for you. You have to write \n at the end, as the examples do. A forgotten \n is the most common reason output runs together on one line. For text built into a variable instead of printed, use sprintf, which takes the same arguments and returns the string.

Python has equivalent tools, and the stand-in below uses them. The % operator on a Python string uses nearly the same placeholders as fprintf, which makes translation easy.

Python fprintf-style output (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Controlling how numbers are displayed

By default MATLAB and Octave show about five significant digits. The format command changes how numbers are displayed; it does not change the stored value.

MATLAB
>> pi
ans =

    3.1416

>> format long
>> pi
ans =

   3.141592653589793

>> format short
>> pi
ans =

    3.1416

Other useful settings are format short g and format long g (compact notation without trailing zeros) and format rat, which shows fractions. format with no arguments returns to the default.

Display precision is a perfect job for the stand-in, because Python lets you see the stored value and the shown value side by side.

Python Stored value versus displayed value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Managing your variables

Three commands help you see and tidy the workspace:

MATLAB
>> who          % names only
>> whos         % names, sizes, bytes and classes
>> clear speed  % remove one variable
>> clear        % remove all variables
>> clc          % clear the Command Window text

exist('speed') tells you whether a name is defined (it returns 1 for a variable). These commands only affect what is in memory and on screen, never files.

Comments

Everything after a % on a line is ignored. Use comments to explain why, not to repeat what the code obviously does.

MATLAB
% This whole line is a comment
rate = 0.07;      % annual interest rate (a comment after code)

%{
A block comment spans several lines.
The %{ and %} markers must be alone on their lines.
%}

Octave also accepts # as a comment character, and #{ ... #} for blocks. Stick to % if you want your files to run in both programs. The first comment lines of a function file become its help text, which brings us to the help system.

Getting help

You rarely have to leave the command line to learn about a function.

MATLAB
>> help sin

prints a short description of sin and examples of use directly in the Command Window. doc sin opens the full documentation page (in MATLAB it opens the Help browser; in Octave it opens the manual). When you do not know the name of the function, search by keyword:

MATLAB
>> lookfor cosine

lookfor scans the first line of every help text for the word and lists matches, so it is slow the first time but useful. MATLAB also has a search box in the toolbar and a function browser that shows the arguments while you type.

Tip: When you write your own functions, put a comment block directly under the function line. help yourfunction will then print it, exactly like the built-in ones.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these is a valid variable name?

    Names must start with a letter and contain only letters, digits and underscores. 2nd_value starts with a digit, total-cost contains a hyphen and end is a keyword.
  2. 2. What does fprintf('Count: %d', 5) leave out that disp adds automatically?

    fprintf prints exactly what the template says, so you must add \n yourself. disp always ends the line.
  3. 3. After format long, what has changed about pi?

    format changes display only. A double always carries the same 64-bit value.
  4. 4. You remember there is a function about cosines but forget its name. Which command searches help texts for the word?

    lookfor searches the first line of help texts for a keyword. help name needs the exact function name.
  5. 5. Which line is a comment in code meant to run in both MATLAB and Octave?

    % works in both. # works only in Octave, and // and -- are not comment markers in either.

Summary

  • Assign with =; variables are created on first use and have no declared type.
  • Names start with a letter, use letters, digits and underscores, are case sensitive and cannot be keywords. Avoid shadowing built-ins such as sum or max.
  • A missing semicolon prints the value, disp prints just the value, and fprintf prints formatted text without adding a newline.
  • format short and format long change only how numbers are shown.
  • who, whos, clear and clc manage the workspace and screen.
  • % starts a comment; help, doc and lookfor find documentation.

Next, meet the data structure behind everything in Everything Is a Matrix.