TExcelTAD
Home › MATLAB / Octave › Commands & Variables

Commands & Variables

A variable is a name for a value in the workspace. You create one simply by assigning to it with =; there is no declaration step and no type keyword. MATLAB works out the type from the value.

matlab · try it yourself
width = 4
height = 2.5;
area = width * height
label = 'rectangle'
width = 4
area = 10
label = rectangle

height exists too, but its assignment ended with a semicolon so nothing was displayed.

Naming rules

Rule Valid Invalid
Start with a letter x1, total 1x, _x
Letters, digits, underscores only max_speed max-speed, max speed
Case sensitive Temp and temp are different
Not a keyword result end, for, if, function
Max length namelengthmax (63) very long names are truncated

You can check a candidate name with isvarname, and the list of reserved words with iskeyword:

matlab · try it yourself
disp(isvarname('speed_2'))
disp(isvarname('2speed'))
disp(iskeyword('end'))
disp(namelengthmax)
1
0
1
63

1 means true and 0 means false; MATLAB displays logical values as numbers.

Warning: Nothing stops you from naming a variable sum, max or i, but doing so hides the built-in function or constant for the rest of the session. After sum = 10, calling sum([1 2 3]) tries to index your variable instead. Pick names like total and maxValue, and use clear sum if it happens.

Reassigning and updating

Assigning to an existing name replaces its value, and the new value can even have a different type or size. To update a variable you write the full expression; MATLAB has no += operator:

matlab · try it yourself
count = 10;
count = count + 1;
count = count * 2;
disp(count)
count = 'now a char array';
disp(count)
22
now a char array

The ans variable

Any expression whose value isn't assigned is stored in ans, which you can then use in the next statement. It is overwritten every time:

matlab · try it yourself
3 + 4
ans * 10
sqrt(ans)
ans = 7
ans = 70
ans = 8.3666

Inspecting the workspace

who lists your variable names, whos adds details, exist tells you whether a name is defined, and clear deletes variables:

matlab · try it yourself
apples = 1; pears = [1 2 3]; label = 'abc';
disp(exist('pears'))
clear pears
disp(exist('pears'))
whos
1
0
Variables visible from the current scope:

variables in scope: top scope

  Attr   Name        Size                     Bytes  Class
  ====   ====        ====                     =====  =====
         apples      1x1                          8  double
         label       1x3                          3  char

Total is 4 elements using 11 bytes

exist returns 1 for a variable and 0 for an unknown name (other codes indicate files and functions). The layout of whos differs between MATLAB and Octave, but both show each variable's name, size, memory and class.

Commands vs. function syntax

Many built-ins can be called in command syntax, without parentheses or quotes: clear x, format long, hold on, close all. That is just shorthand for the function form with char arguments: clear('x'), format('long'). Use the function form when the argument is stored in a variable.

Built-in constants

Name Value
pi 3.14159…
i, j The imaginary unit √-1
Inf Infinity, e.g. 1/0
NaN "Not a Number", e.g. 0/0
eps Distance from 1.0 to the next double (about 2.2e-16)
true, false Logical 1 and 0
matlab · try it yourself
fprintf('pi = %.6f\n', pi);
fprintf('1/0 = %f, 0/0 = %f\n', 1/0, 0/0);
fprintf('eps = %g\n', eps);
pi = 3.141593
1/0 = Inf, 0/0 = NaN
eps = 2.22045e-16

Test yourself

Which is a valid MATLAB variable name?

  1. 2ndValue
  2. second-value
  3. second_value
  4. for

How do you add 5 to a variable n?

  1. n += 5
  2. n = n + 5
  3. n++5
  4. add(n, 5)

What happens if you run max = 3 and then max([4 9 2])?

  1. It returns 9
  2. It returns 3
  3. It tries to index the variable max and fails
  4. MATLAB refuses to create the variable