MATLAB & GNU Octave Module 1 – Start here: MATLAB, Octave and a working setup
Command window basics: variables, ans and display
Use the Octave command window: predict operator precedence, read how numbers and arrays are shown, manage variables, avoid shadowed names and find help.
What you will learn
- Evaluate expressions and predict operator precedence, including unary minus, powers and transposes
- Create, inspect and clear variables, and read Octave's display of numbers, empty arrays and logicals
- Find help inside Octave with help, lookfor, doc and which
- Detect and repair names that shadow built-in functions such as i, j, pi and sum
Before you start
What you’ll learn · Before you start
What you will learn
- Evaluate expressions and predict operator precedence, including unary minus, powers and transposes
- Create, inspect and clear variables, and read Octave's display of numbers, empty arrays and logicals
- Find help inside Octave with help, lookfor, doc and which
- Detect and repair names that shadow built-in functions such as i, j, pi and sum
Before you start
On this page
Type -2^2 at Octave’s prompt and it answers ans = -4; type 2^3^2 and it answers 64, not the 512 of a maths
book. The prompt evaluates every line by a few fixed rules, and the same rules decide what a script computes, so they
are worth learning before anything else.
Below you follow a line through the prompt, predict how Octave groups operators and reads spaces inside brackets, create, list and clear variables, tell what is stored from what is shown, repair names that hide built-in functions, and use Octave’s own help to answer questions without leaving the command window.
The prompt evaluates each line, shows its value and keeps it in ans
Octave’s prompt in a terminal reads octave:1>, numbered: each line you type is evaluated, its value is kept, and
the value is shown unless the line ends in a semicolon. A value without a name of its own goes into
ans: The variable in which MATLAB and Octave keep the most recent result that has no name of its own. An assignment such as x = 5 leaves it unchanged.. Follow two lines through it:
The drawing shows the whole scene; its 7 steps are listed below.
Every step as text
- A line without a name. At the prompt octave:1> you type 3 * 4 + 2 and press Enter. Nothing is computed until the whole line is in.
- Evaluated. Octave applies the operators by precedence, the multiplication first, and gets 14.
- Kept in ans. The line gives the value no name, so Octave keeps it in ans, the variable for the last result that has no name of its own.
- Shown. The line does not end in a semicolon, so Octave shows the value with its name, ans = 14.
- The next prompt. The prompt returns as octave:2>. Typing ans / 2 there would use the 14 and give ans = 7.
- A line with a name. Now you type area_m2 = pi * 0.006^2; with a semicolon at the end. The value, 1.1310e-04, goes into area_m2, and ans is left as it was.
- Nothing shown. The semicolon tells Octave not to show the value, so it goes straight back to the prompt. Typing area_m2 alone shows it, area_m2 = 1.1310e-04.
The session below types those lines and four more. Each line follows the prompt that read it, and what Octave printed comes under it:
from session import prompt, version
version()
prompt("prompt_basics.m") Output
# GNU Octave (aarch64-apple-darwin25.4.0) version 11.3.0 $ octave-cli --quiet octave:1> 3 * 4 + 2 ans = 14 octave:2> ans / 2 ans = 7 octave:3> area_m2 = pi * 0.006^2; octave:4> area_m2 area_m2 = 1.1310e-04 octave:5> area_mm2 = area_m2 * 1e6 area_mm2 = 113.10 octave:6> ans ans = 7
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 basics_session.py
Three rules show in it:
- A value without a name goes into
ans.3 * 4 + 2gaveans = 14, andans / 2used it to giveans = 7. - An assignment keeps the value in its name, and
ansstays as it was. Afterarea_m2 = …andarea_mm2 = …, typingansstill showed 7. - A semicolon at the end hides the value.
area_m2 = pi * 0.006^2;showed nothing; typingarea_m2alone showedarea_m2 = 1.1310e-04. A script follows the same rule, so a script without semicolons prints every value it makes.
Relying on ans in a script
ans changes every time a line without a name runs, so a script that reads ans three lines later may get another
value than you expect. Give every result you use again a name of its own, such as area_mm2.
Checkpoint
Check: The prompt, ans and the semicolon
Power binds tighter than unary minus, and powers group from the left
Before computing, Octave groups the operators of a line by operator precedence: The rules that decide which operators of an expression are applied first. In MATLAB and Octave, ^ binds tighter than unary minus, so -2^2 is -4..
Two rules surprise people: ^ binds tighter than a minus sign in front of a number, and operators of the same level
group from the left. Step through the groups Octave forms for -2^2 and 2^3^2:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- -2^2 as a tree. Power binds tighter than unary minus, so Octave groups 2^2 first and puts the minus above it. The minus belongs to the whole power, not to the 2.
- The power first. The lowest group runs first, 2^2, which is 4.
- Then the minus. The minus applies to that result, so -2^2 prints ans = -4. Write (-2)^2 for the square of minus two, which is 4.
- 2^3^2 as a tree. Both operators are powers, of the same level, and Octave groups operators of one level from the left. So the first ^ forms the group 2^3, and the second ^ takes it as its base.
- The left group first. The left group runs first: 2^3 is 8, the base of the second power.
- Then the second power. 8^2 is 64, and Octave prints ans = 64. Maths books read a tower of powers from the top, 2^(3^2) = 512, so write the parentheses you mean.
The prompt confirms both trees, and the last lines show the transpose ', which turns a row into a column:
from session import prompt, version
version()
prompt("precedence.m") Output
# GNU Octave (aarch64-apple-darwin25.4.0) version 11.3.0 $ octave-cli --quiet octave:1> -2^2 ans = -4 octave:2> (-2)^2 ans = 4 octave:3> 2^-1 ans = 0.5000 octave:4> 2^3^2 ans = 64 octave:5> 2^(3^2) ans = 512 octave:6> 2 * 3^2 ans = 18 octave:7> 1:3+1 ans = 1 2 3 4 octave:8> x = [1 2 3]; octave:9> x' ans = 1 2 3
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 precedence_session.py
The Octave manual lists the levels from the tightest down, and MathWorks documents the same order for MATLAB:
| Operators, tightest first | What they do |
|---|---|
' .' ^ .^ |
transposes and powers, grouped from the left |
-x +x ~x |
unary minus and plus, logical not |
* / \ .* ./ .\ |
multiply and divide |
+ - |
add and subtract |
: |
ranges, as in 1:4 |
< <= == ~= >= > |
compare |
&, then | |
element-wise and, or |
&&, then || |
short-circuit and, or |
Two rows explain the rest of the run: 2^-1 is 0.5000, because the minus belongs to the exponent, and 1:3+1 adds
before it builds the range, so it gives 1 to 4.
Writing 2^3^2 for two to the ninth
Octave and MATLAB compute 2^3^2 as (2^3)^2, which is 64. For 512, two to the power nine, write 2^(3^2), as
the run does. Parentheses cost nothing and make the order plain to every reader.
Checkpoint
Check: Operator precedence
Inside brackets, a space can start a new element
Inside square brackets, a space or a comma separates the elements of a row. That makes the spaces around a minus sign matter:
from session import prompt, version
version()
prompt("brackets.m") Output
# GNU Octave (aarch64-apple-darwin25.4.0) version 11.3.0 $ octave-cli --quiet octave:1> a = 3; b = 2; octave:2> [a -b] ans = 3 -2 octave:3> [a - b] ans = 1 octave:4> [a- b] ans = 1 octave:5> [a, -b] ans = 3 -2 octave:6> [a (b)] ans = 3 2 octave:7> (a -b) ans = 1 octave:8> [1 +2] ans = 1 2
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 brackets_session.py
With a = 3 and b = 2, [a -b] is the row 3 -2: a space before the minus and none after it make -b a new
element. [a - b] and [a- b] are the single number 1, because a minus with a space after it is a subtraction.
[a (b)] is the row 3 2, two elements, not a indexed by b. The rule belongs to brackets: (a -b) in
parentheses is the subtraction 1 again, and a plus sign follows the same rule as a minus, so [1 +2] is the row
1 2.
| You type | Octave reads | Result |
|---|---|---|
[a -b] |
two elements, a and -b |
3 -2 |
[a - b] |
one subtraction | 1 |
[a, -b] |
two elements, with a comma | 3 -2 |
[a (b)] |
two elements, a and (b) |
3 2 |
Say what you mean with commas and parentheses
Write [a, -b] for two elements and (a - b) for a subtraction. Both read the same in MATLAB and Octave, whatever
the spacing, and nobody has to remember the rule.
Checkpoint
Check: Spaces inside brackets
Names hold values, and the workspace lists them
Every name you assign at the prompt lives in the workspace: The set of variables that exist at the prompt and in the scripts it runs. who and whos list it, and clear removes names from it. until you clear it or close Octave. A name starts with a letter, may hold letters, digits and underscores, and is case-sensitive. These lines compute the cross-section of a 12 mm rod and then look at the workspace:
from session import prompt, version
version()
prompt("names.m", errors=1) Output
# GNU Octave (aarch64-apple-darwin25.4.0) version 11.3.0
$ octave-cli --quiet
octave:1> force_kN = 15;
octave:2> diameter_mm = 12;
octave:3> area_mm2 = pi * diameter_mm^2 / 4
area_mm2 = 113.10
octave:4> who
Variables visible from the current scope:
area_mm2 diameter_mm force_kN
octave:5> whos
Variables visible from the current scope:
variables in scope: top scope
Attr Name Size Bytes Class
==== ==== ==== ===== =====
area_mm2 1x1 8 double
diameter_mm 1x1 8 double
force_kN 1x1 8 double
Total is 3 elements using 24 bytes
octave:6> exist('area_mm2')
ans = 1
octave:7> Area_mm2
error: 'Area_mm2' undefined near line 1, column 1
octave:8> clear area_mm2
octave:9> exist('area_mm2')
ans = 0
octave:10> isvarname('2nd_try')
ans = 0
octave:11> namelengthmax
ans = 63
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 names_session.py
What the session shows:
wholists the names;whosadds each one’s size, bytes and class. All three are 1x1doublevalues of 8 bytes, 24 bytes in all.existreturns a code. 1 means a variable; afterclear area_mm2it returned 0, nothing of that name. The codes are the same in MATLAB: 2 means a file, and 5, a built-in function, comes back later in this lesson.- Names are case-sensitive.
Area_mm2is a different name, never assigned, so Octave answered'Area_mm2' undefined. - Some names are not allowed.
isvarname('2nd_try')is 0 because a name cannot start with a digit, andnamelengthmaxsays names may have up to 63 characters.
clear with a name removes that name; clear alone empties the whole workspace, which is why a script that starts
with clear cannot rely on anything typed before it.
Key idea
A name holds its value until clear removes it; who, whos and exist tell you what the workspace holds at any
moment.
Checkpoint
Check: Names and the workspace
Display is not data: format changes what you see, not what is stored
Octave shows numbers in a short format by default, five significant digits. The value behind the display keeps all its digits, and the next session shows how far apart the two can be:
from session import prompt, version
version()
prompt("display_demo.m") Output
# GNU Octave (aarch64-apple-darwin25.4.0) version 11.3.0 $ octave-cli --quiet octave:1> p = pi p = 3.1416 octave:2> format long octave:3> p p = 3.141592653589793 octave:4> format short octave:5> p p = 3.1416 octave:6> big = 123456789 big = 1.2346e+08 octave:7> big - 123456780 ans = 9 octave:8> v = [1 1000.5] v = 1.0000e+00 1.0005e+03 octave:9> none = zeros(0, 3) none = [](0x3) octave:10> ok = [3 7 9] > 5 ok = 0 1 1 octave:11> class(ok) ans = logical
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 display_session.py
format longshows more digits of the same value.pshowed 3.1416, then 3.141592653589793, then 3.1416 again; the stored value never changed. The Octave manual puts it plainly: the command “only affects the display of numbers, not how they are stored or computed”.- A short display can hide the digits that matter.
big = 123456789showed1.2346e+08, yetbig - 123456780is exactly 9: every digit was stored. - A row with very different sizes is shown in e-notation.
[1 1000.5]appeared as1.0000e+00 1.0005e+03. - Empty arrays show their size.
zeros(0, 3)showed[](0x3): zero rows and three columns. - Comparisons give logical values, shown as
0and1withclasslogical.
MATLAB lays the same values out differently: its default adds blank lines around results, and MathWorks’ examples show
a common scale factor above a row of very different sizes. So code that checks a result compares values, as
big - 123456780 == 9 does, never the text that one program displays.
Checking a result by its displayed text
1.2346e+08 on the screen is not the value; it is five digits of it. Compare numbers with numbers, within a
tolerance where rounding can creep in, and print with fprintf and a stated format when the text itself matters.
Checkpoint
Check: Display and stored value
A name can hide a function: i, j, pi and sum
i, j, pi and sum are functions, and a variable of the same name hides each of them. This is called
shadowing: When a variable or a file with the same name as a function hides it, so that the name no longer calls the function, as sum = 0 hides sum()., and it is the classic bug of the command window:
from session import prompt, version
version()
prompt("shadowing.m", errors=1) Output
# GNU Octave (aarch64-apple-darwin25.4.0) version 11.3.0
$ octave-cli --quiet
octave:1> z = 3 + 2*i
z = 3 + 2i
octave:2> i = 5;
octave:3> z = 3 + 2*i
z = 13
octave:4> z = 3 + 2i
z = 3 + 2i
octave:5> sum = 0;
octave:6> sum([4 5 6])
error: sum(6): out of bound 1 (dimensions are 1x1) (note: variable 'sum' shadows function)
octave:7> which sum
'sum' is a variable
octave:8> clear sum
octave:9> sum([4 5 6])
ans = 15
octave:10> exist('pi')
ans = 5
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 shadowing_session.py
iis the imaginary unit until you assign it.3 + 2*iwas the complex number3 + 2i; afteri = 5the same line gave 13. The literal2istays complex whateveriholds, so write1ifor the unit and use names such ask,mornfor loop counters.sum = 0breakssum(...). With a variable calledsum,sum([4 5 6])asks for elements 4, 5 and 6 of a 1x1 variable. Octave 11.3 says so, and adds(note: variable 'sum' shadows function).whichandexistfind the culprit.which sumanswered'sum' is a variable, andexist('pi')returned 5, a built-in function: A function that is part of the program itself, compiled into it rather than read from an .m file, such as sum or det. exist returns 5 for one., because nothing hidespiin that session.clear namerepairs it. Afterclear sum,sum([4 5 6])gave 15 again.
Using i and j as loop counters
for i = 1:3 leaves i = 3 behind, and a later z = 2*i gives 6 instead of the complex 0 + 2i. Use k for the
counter and 1i for the unit, and the two can never collide.
Checkpoint
Check: Names that hide functions
help, lookfor and which answer questions without leaving Octave
Octave’s help is inside Octave. Which command to use depends on what you already know:
| You know | Type |
|---|---|
| the function’s name | help det for its help text, doc det for its page of the manual |
| only the topic | lookfor determinant, which searches the first sentence of every help text |
| a name, and want to know what it is | which det, or exist('det') for the code |
Here is each of them at the prompt:
from session import prompt, version
version()
prompt("help_tour.m") Output
# GNU Octave (aarch64-apple-darwin25.4.0) version 11.3.0
$ octave-cli --quiet
octave:1> which det
'det' is a built-in function from the file libinterp/corefcn/det.cc
octave:2> get_first_help_sentence('det')
ans = Compute the determinant of A.
octave:3> lookfor determinant
det Compute the determinant of A.
octave:4> help namelengthmax
'namelengthmax' is a function from the file /opt/homebrew/Cellar/octave/11.3.0_1/share/octave/11.3.0/m/miscellaneous/namelengthmax.m
-- N = namelengthmax ()
Return the MATLAB compatible maximum variable name length.
Octave is capable of storing strings up to 2^{31} - 1 in length. However
for MATLAB compatibility all variable, function, and structure field names
should be shorter than the length returned by ‘namelengthmax’. In
particular, variables stored to a MATLAB file format (‘*.mat’) will have
their names truncated to this length.
Additional help for built-in functions and operators is
available in the online version of the manual. Use the command
'doc <topic>' to search the manual index.
Help and information about Octave is also available on the WWW
at https://www.octave.org and https://octave.discourse.group/c/help/
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 help_session.py
which det says that det is a built-in function, written in C++ inside Octave, while help namelengthmax starts
with the file it comes from, an .m file of Octave’s own. get_first_help_sentence('det') returns the one sentence
lookfor searches, Compute the determinant of A., and lookfor determinant found det by that sentence. A help
text starts with the call forms, here -- N = namelengthmax (), then says what the function returns. When
lookfor finds nothing, lookfor -all searches the whole help texts instead of their first sentences. help
alone explains how to use help, an operator needs quotes, as in help "+", and doc det shows det’s entry of the
Octave manual, through the Info program when Octave runs in a terminal.
Checkpoint
Check: Help inside Octave
Practise: predict, then type
Octave itself shows whether you got each of these right, so do them once it runs on your computer:
- Write down what
-3^2,2^-2,[5 -1]and[5 - 1]give, then type them at the prompt and compare. - Assign
area_mm2 = pi * 12^2 / 4, then usewho,whosandexist('area_mm2')before and afterclear area_mm2. - Write
pressure_table.m, which converts 1.013, 2.5 and 10 bar to kilopascals (1 bar is 100 kPa) and prints each with two decimals,101.30 kPa,250.00 kPaand1000.00 kPa, withfprintf. Before you assign a name, check thatexistreturns 0 for it.
The session below asks up to twelve of this page’s questions, many of them “what does this print?”, in the order your answers call for, and explains each answer on the spot:
Practice that adapts to you
Practise this lesson
17 questions about 7 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Interview questions
Warm-up: what does a semicolon at the end of a line do, and what is ans?
A semicolon at the end of a line stops Octave and MATLAB from showing the line’s value; the value is still computed
and kept. Without it, the command window shows the result with its name, as in area_mm2 = 113.10. ans is the
variable that holds the most recent value that had no name of its own: typing 3 * 4 + 2 sets ans to 14, and an
assignment such as x = 5 leaves ans unchanged. In scripts the same rules apply, so a line without a semicolon
prints its value in the middle of the output, and code that reads ans several lines later may get a value from
another line. Give results you need again a name of their own, and end lines with semicolons unless you want to see
the value.
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
Fresher to mid
A colleague's script stops with "error: sum(6): out of bound 1 (dimensions are 1x1)". The same lines worked yesterday. How do you find the cause, fix it, and keep it from coming back?
-
Mid to senior
Your course checks answers by comparing what each script prints with expected text made in MATLAB. A student's correct Octave answer fails. Explain why, and redesign the check so that correct answers pass in either program.
Key takeaways
- The prompt evaluates each line, keeps a value without a name in
ans, leavesansalone on assignments, and shows every value unless the line ends in a semicolon. ^binds tighter than unary minus and powers group from the left, so-2^2is -4 and2^3^2is 64; write parentheses, such as2^(3^2)for 512, whenever the order matters.- Inside brackets a space before a minus starts a new element:
[a -b]is a row of two,[a - b]a single difference, and commas say which you mean. who,whosandexistshow what the workspace holds, names are case-sensitive and up to 63 characters long, andclearremoves names.formatchanges only the display:1.2346e+08was all of 123456789 underneath, so code compares values, never displayed text.- A variable named
i,piorsumhides the function of that name untilclearremoves it, andhelp,lookfor,docandwhichanswer questions from inside Octave.
Terms in this lesson
- ans
- The variable in which MATLAB and Octave keep the most recent result that has no name of its own. An assignment such as x = 5 leaves it unchanged.
- built-in function
- A function that is part of the program itself, compiled into it rather than read from an .m file, such as sum or det. exist returns 5 for one.
- operator precedence
- The rules that decide which operators of an expression are applied first. In MATLAB and Octave, ^ binds tighter than unary minus, so -2^2 is -4.
- shadowing
- When a variable or a file with the same name as a function hides it, so that the name no longer calls the function, as sum = 0 hides sum().
- workspace
- The set of variables that exist at the prompt and in the scripts it runs. who and whos list it, and clear removes names from it.
References
- GNU Octave manual: Operator Precedence (The Octave Project Developers)
- GNU Octave manual: Terminal Output (format, disp) (The Octave Project Developers)
- GNU Octave manual: Status of Variables (who, whos, clear, exist) (The Octave Project Developers)
- GNU Octave manual: Getting Help (help, doc, lookfor) (The Octave Project Developers)
- GNU Octave manual: Customizing the Prompt (The Octave Project Developers)
- Operator Precedence (MATLAB) (MathWorks)
- format: set output display format (MATLAB) (MathWorks)
- which: locate functions and files (MATLAB) (MathWorks)
- exist: check existence of variable, script, function, folder or class (MATLAB) (MathWorks)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress