Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

MATLAB & GNU Octave  Module 1 – Start here: MATLAB, Octave and a working setup

Scripts, the current folder and the search path

Write Octave and MATLAB scripts with comments and sections, control which file runs through the current folder and the search path, and build portable paths.

  • Beginner
  • 25 minutes
  • Examples run with octave 11.3.0 and Python 3.14.8
  • By MySmartCoPilot
Free lesson, Pro answers: 25 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Write and run script files with comments and %% sections
  • Predict which file runs from the current folder, the search path and the function precedence order
  • Build file paths that work on Windows, macOS and Linux
  • Organise a small research project so that it runs from any folder

Before you start

What you’ll learn · Before you start

What you will learn

  • Write and run script files with comments and %% sections
  • Predict which file runs from the current folder, the search path and the function precedence order
  • Build file paths that work on Windows, macOS and Linux
  • Organise a small research project so that it runs from any folder

Before you start

On this page

A script that reads data/loads.txt works when you run it from its own folder and stops with load: unable to find file data/loads.txt when a colleague runs it from the folder above. Which file Octave runs, and which file a script opens, both depend on two things: the current folder and the search path.

Below you write a script with comments and sections, follow the order in which Octave looks up a name and see one stray file hide a function, add a folder of tools to the search path for one session, build file paths that work on Windows, macOS and Linux, and organise a small project that runs from any folder.

A script is a file of commands that runs in your workspace

A script file: A text file of commands ending in .m that runs as if its lines were typed at the prompt, in the same workspace, so its variables remain after it ends. is a plain text file of commands ending in .m. Running it is like typing its lines at the prompt, one after another. This one follows a cup of tea as it cools, by Newton’s law of cooling, and uses all three kinds of comment:

cooling.m: comments, a block comment and %% sections M · cooling.m
%% cooling.m: a cup of tea cooling in a room, by Newton's law of cooling
% Each line that starts with %% begins a section, which an editor can run on
% its own. A % starts a comment that runs to the end of the line.
%{
  The model: T(t) = T_room + (T0 - T_room) * exp(-k * t),
  with t in minutes and k, the cooling constant, per minute.
%}

%% Inputs
T_room = 25;                 % room temperature, degrees C
T0 = 90;                     % temperature of the fresh tea, degrees C
k = 0.05;                    % cooling constant, per minute

%% Temperature after 10, 20 and 30 minutes
t = [10 20 30];
T = T_room + (T0 - T_room) * exp(-k * t);
fprintf('After %2d min: %.1f C\n', [t; T]);
  • % starts a comment that runs to the end of the line, in MATLAB and Octave alike.
  • %{ and %}, each alone on its line, enclose a block comment, here the model in words.
  • %% at the start of a line begins a code section: A part of a script that begins with a line starting with %%. MATLAB's editor can run one section at a time, and Octave's publish uses sections as headings.. MATLAB’s editor runs one section at a time with Run Section, and Octave’s publish turns sections into the headings of a report.

# comments work only in Octave, as the first lesson’s labels showed. Here is the script run by its name at the prompt, followed by two more lines:

cooling.m, run at the Octave prompt, GNU Octave 11.3.0 Python · scripts_session.py
from session import prompt, version

version()
prompt("cooling_prompt.m")

Output

# GNU Octave (aarch64-apple-darwin25.4.0) version 11.3.0
$ octave-cli --quiet
octave:1> cooling
After 10 min: 64.4 C
After 20 min: 48.9 C
After 30 min: 39.5 C
octave:2> who
Variables visible from the current scope:

T       T0      T_room  k       t

octave:3> T_room
T_room = 25

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 scripts_session.py

Typing cooling ran the file and printed 64.4, 48.9 and 39.5 degrees after 10, 20 and 30 minutes. Then who listed T, T0, T_room, k and t: the script’s variables stayed in the workspace, because a script has no workspace of its own. That is handy at the prompt, where you can look at every value afterwards, and a trap in larger work, where one script can overwrite another’s variables.

Name a script after what it does

A script runs under its file name, so the name must be a valid variable name: cooling.m runs as cooling, while tea-cooling.m cannot be run by its name, because tea-cooling reads as a subtraction.

Checkpoint

Check: Script files, comments and sections

  1. Question 1 of 2 Which of these lines of cooling.m starts a code section?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: %% Inputs

    %% at the start of a line begins a section; the rest of the line is its title. A single % is a comment, and %{ with %} encloses a block comment.

  2. Question 2 of 2 After typing cooling at the prompt, what does typing T_room show?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: T_room = 25

    A script has no workspace of its own: T, T0, T_room, k and t stayed after the run, and T_room shows 25.

Octave looks for a name in a fixed order, and a file can hide a function

When a line uses a name such as mean, Octave searches for it in a fixed order and takes the first match. Here it searches for mean from report.m, in a folder where a beginner saved a first script as mean.m:

Interactive · stage by stage Where Octave looks when report.m calls mean Step through the places Octave checks, in order, first with the stray mean.m in the folder, then without it.
Where Octave looks when report.m calls mean, step 7 of 7. Showing A variable of that name?, A function in this file?, In the current folder? (no mean.m any more), On the search path? (statistics/mean.m found), Built into Octave?, Use what was found (mean(loads_kN) = 15). In focus: Built into Octave?.found mean.mfound Octave's meanA variable of that name?the workspace comes firstA function in this file?then private/ beside itIn the current folder?no mean.m any moreOn the search path?statistics/mean.m foundBuilt into Octave?compiled functionsUse what was foundmean(loads_kN) = 15

The drawing shows the whole scene; its 7 steps are listed below.

Every step as text
  1. A variable?. report.m calls mean(loads_kN). Octave first looks for a variable called mean, because a variable hides any function. There is none.
  2. This file. Next it looks for a function of that name inside report.m itself, or in a folder called private next to it. There is none.
  3. The current folder. The current folder, shadow_demo, holds a file called mean.m, so Octave stops looking. The file it found is a script.
  4. The wrong mean. A script takes no inputs, so the call mean(loads_kN) fails with invalid call to script, and Octave warns that the file shadows a core library function.
  5. Renamed. After mean.m is renamed readings_average.m, the current folder holds no file called mean.m, and the search goes on.
  6. The search path. The search path lists Octave's own folders, and statistics/mean.m is found there. report.m prints Average load 15 kN.
  7. Built-in functions. The Octave manual puts built-in functions such as sum after the path, so even a sum.m in the current folder would hide the built-in sum. A name found nowhere is undefined.

Here are the two files and the run, then the same run after the stray file is renamed:

shadow_demo/report.m: an average with the mean function M · shadow_demo/report.m
% report.m: the average of three loads, with the mean function.
loads_kN = [12 15 18];
fprintf('Average load: %g kN\n', mean(loads_kN));
shadow_demo/mean.m: a script saved under a function's name M · shadow_demo/mean.m
% mean.m: a first script, saved under a name a function already has.
readings = [2 4 6];
fprintf('Average of the readings: %g\n', sum(readings) / numel(readings));
A stray mean.m, then renamed, GNU Octave 11.3.0 Python · shadow_session.py
from session import run, version

version()
run("""
cd shadow_demo && octave-cli --no-init-all --eval "which mean"
!cd shadow_demo && octave-cli --no-init-all report.m
cd shadow_demo && octave-cli --no-init-all --eval "which -all mean"
cd shadow_demo && mv mean.m readings_average.m
cd shadow_demo && octave-cli --no-init-all report.m
cd shadow_demo && octave-cli --no-init-all --eval "which mean"
""")

Output

# GNU Octave (aarch64-apple-darwin25.4.0) version 11.3.0
$ cd shadow_demo && octave-cli --no-init-all --eval "which mean"
warning: function shadow_demo/mean.m shadows a core library function
'mean' is a script from the file shadow_demo/mean.m
$ cd shadow_demo && octave-cli --no-init-all report.m
warning: function shadow_demo/mean.m shadows a core library function
error: invalid call to script shadow_demo/mean.m
error: called from
    mean
    report at line 3 column 1
[exit status 1]
$ cd shadow_demo && octave-cli --no-init-all --eval "which -all mean"
warning: function shadow_demo/mean.m shadows a core library function
warning: which: '-all' not yet implemented - only the first result will be returned
'mean' is a script from the file shadow_demo/mean.m
$ cd shadow_demo && mv mean.m readings_average.m
$ cd shadow_demo && octave-cli --no-init-all report.m
Average load: 15 kN
$ cd shadow_demo && octave-cli --no-init-all --eval "which mean"
'mean' is a function from the file /opt/homebrew/Cellar/octave/11.3.0_1/share/octave/11.3.0/m/statistics/mean.m

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 shadow_session.py

which mean named the script in the folder, and Octave warned that it “shadows a core library function”. The call mean(loads_kN) then failed with invalid call to script, because a script takes no inputs. After mv renamed the file to readings_average.m, report.m printed Average load: 15 kN, and which mean found Octave’s own statistics/mean.m.

The order is a function precedence order: The fixed order in which MATLAB and Octave look up a name: variables first, then functions in the same file and private folders, then the current folder and the search path.. Octave’s manual lists it from functions in the same file and private folders down to the folders of the search path and the built-in functions, and a variable comes before all of them, as sum = 0 showed in the previous lesson. MathWorks documents the same outline for MATLAB: variables first, then functions in the same file, private functions, the current folder and the rest of the path.

The third command shows a portability gap: Octave 11.3 answers which -all mean with '-all' not yet implemented and gives only the first match, while MATLAB’s which -all lists every file of that name on the path.

Saving a script under a function's name

mean.m, sum.m, plot.m or max.m in your folder hides the function for every script run there. Before you save a new file, type which name with the name you want: an answer that names a built-in function or a file of Octave’s own means the name is taken.

Checkpoint

Check: The order of name lookup

  1. Question 1 of 2 A folder holds a function file sum.m, and a script in that folder calls sum([1 2 3]). Which sum runs?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The sum.m in the folder

    The first match wins, and the current folder is searched before the built-in functions. That is how a stray mean.m hid Octave's mean in the lesson.

  2. Question 2 of 2 Why did mean(loads_kN) fail with invalid call to script in shadow_demo?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Octave found the script mean.m in the folder first, and a script takes no inputs

    which mean named the script in the folder. Renaming it to readings_average.m let the search reach Octave's mean, and report.m printed Average load: 15 kN.

The search path decides which other folders count

Octave finds a file in the current folder, and beyond it only in the folders of its search path: The list of folders in which MATLAB and Octave look for function and script files. It starts with the current folder; addpath and rmpath change it for the session., which starts with the current folder and continues with Octave’s own folders. addpath adds a folder for the rest of the session, rmpath removes it, and genpath lists a folder with all its subfolders. This session uses a small folder of helper functions, tools/ with a subfolder tools/units/:

tools/to_mpa.m: pascals to megapascals M · tools/to_mpa.m
function stress_MPa = to_mpa(stress_Pa)
  % to_mpa: converts a stress from pascals to megapascals.
  stress_MPa = stress_Pa / 1e6;
end
Adding and removing a folder of tools, GNU Octave 11.3.0 Python · path_session.py
from session import prompt, version

version()
prompt("path_prompt.m", flags="--no-init-all")

Output

# GNU Octave (aarch64-apple-darwin25.4.0) version 11.3.0
$ octave-cli --no-init-all --quiet
octave:1> exist('to_mpa')
ans = 0
octave:2> addpath('tools')
octave:3> exist('to_mpa')
ans = 2
octave:4> which to_mpa
'to_mpa' is a function from the file tools/to_mpa.m
octave:5> to_mpa(132.6e6)
ans = 132.60
octave:6> rmpath('tools')
octave:7> exist('to_mpa')
ans = 0
octave:8> genpath('tools')
ans = tools:tools/units
octave:9> old_path = path();
octave:10> addpath(genpath('tools'))
octave:11> to_mpa(kn_to_n(15) / 113.1e-6)
ans = 132.63
octave:12> path(old_path);
octave:13> exist('kn_to_n')
ans = 0

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 path_session.py

Before addpath('tools'), exist('to_mpa') was 0: the function’s file is in a subfolder, which the search does not enter. Afterwards it was 2, a file, and which showed where. rmpath took it away again. genpath('tools') returned tools:tools/units, the folder and its subfolder separated by pathsep, a colon on macOS and Linux.

The last five lines are the pattern to keep: save the path with old_path = path(), add what the work needs with addpath(genpath('tools')), do the work, here a stress of 132.63 MPa from the two helpers, and put the old path back with path(old_path), so the next project starts clean.

Saving the path for every session with savepath

savepath writes the current path into a startup file, so it changes every later session, including other projects that never wanted those folders. Set the path in the project, as above, and restore it when done. MathWorks also advises against changing the path while code runs, because MATLAB then recompiles code.

Checkpoint

Check: The search path

  1. Question 1 of 2 Before addpath('tools'), exist('to_mpa') returned 0. What did it return after it?

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 2

    2 is the code for a file: to_mpa.m was now in a folder of the search path. After rmpath('tools') it was 0 again.

  2. Question 2 of 2 genpath('tools') returned tools:tools/units. What is the colon?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: pathsep, the separator between folders of a path list on macOS and Linux

    genpath lists a folder and all its subfolders in one text, separated by pathsep, which addpath then takes in one call.

fullfile builds paths that work on every system

data/raw/loads.txt is a path for macOS and Linux; Windows writes data\raw\loads.txt. Rather than typing either separator, let the program choose it:

Building and splitting paths, GNU Octave 11.3.0 Python · paths_session.py
from session import prompt, version

version()
prompt("paths_prompt.m", flags="--no-init-all")

Output

# GNU Octave (aarch64-apple-darwin25.4.0) version 11.3.0
$ octave-cli --no-init-all --quiet
octave:1> f = fullfile('data', 'raw', 'loads.txt')
f = data/raw/loads.txt
octave:2> filesep
ans = /
octave:3> pathsep
ans = :
octave:4> [folder, name, ext] = fileparts(f)
folder = data/raw
name = loads
ext = .txt
octave:5> fullfile('data/', '/raw', 'loads.txt')
ans = data/raw/loads.txt

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 paths_session.py

fullfile('data', 'raw', 'loads.txt') joined the parts with filesep, the separator of the system, / on the Mac that recorded these runs; on Windows the Octave manual says fullfile uses backslashes. It also cleaned up doubled separators: fullfile('data/', '/raw', 'loads.txt') gave the same data/raw/loads.txt. fileparts works the other way, splitting a path into its folder data/raw, its name loads and its extension .txt. On Windows, filesep('all') returns both slashes, the separators Octave accepts there, so a path read from a file may contain / or \; split it with fileparts rather than by searching for one character.

Task Portable Fragile
Join folder and file names fullfile('data', 'raw', 'loads.txt') 'data/raw/loads.txt'
Split a path [folder, name, ext] = fileparts(f) cutting the text at '/'
Find the separator filesep assuming / or \

Checkpoint

Check: Portable file paths

  1. Question 1 of 2 What does this give on macOS or Linux?

    Read the code, then choose one answer.

    fullfile('results', 'run1', 'stress.txt')
    Show the answer: Question 1 of 2

    Answer: ans = results/run1/stress.txt

    fullfile joins its parts with the system's separator, so the same line gives results/run1/stress.txt here and results\run1\stress.txt on Windows.

  2. Question 2 of 2 After [folder, name, ext] = fileparts('data/raw/loads.txt'), what is name?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: loads

    fileparts gives the folder, the name and the extension: data/raw, loads and .txt, as the session showed.

A project that finds its own files runs from any folder

The script of the opening, analysis_fragile.m, opens data/loads.txt, a path relative to the current folder, so it works only when the current folder is the project’s. run_analysis.m starts by asking where it is, then builds every path from there:

project/analysis_fragile.m: paths relative to the current folder M · project/analysis_fragile.m
% analysis_fragile.m: works only when the current folder is the project's.
loads_kN = load('data/loads.txt');
fprintf('Read %d loads\n', numel(loads_kN));
project/run_analysis.m: paths built from the script's own folder M · project/run_analysis.m
% run_analysis.m: the stress in a 12 mm rod for each load in data/loads.txt,
% written to results/stress.txt. It finds its own folder first, so it works
% from any current folder.
here = fileparts(mfilename('fullpath'));
loads_kN = load(fullfile(here, 'data', 'loads.txt'));
area_mm2 = pi * 12^2 / 4;
stress_MPa = loads_kN * 1e3 / area_mm2;      % N per mm^2 is MPa
out_dir = fullfile(here, 'results');
if ~exist(out_dir, 'dir')
  mkdir(out_dir);
end
fid = fopen(fullfile(out_dir, 'stress.txt'), 'w');
fprintf(fid, '%4.0f kN: %6.1f MPa\n', [loads_kN'; stress_MPa']);
fclose(fid);
fprintf('Wrote %d stresses to %s\n', numel(stress_MPa), fullfile('results', 'stress.txt'));

Step through how run_analysis.m finds its files when it is started from another folder:

Interactive · step by step How run_analysis.m finds its own files Step through one run started from another folder, and watch each path the script builds from its own location.
How run_analysis.m finds its own files, step 5 of 5. Showing The current folder (any folder, same result), run_analysis.m, here (fileparts(mfilename(…))), data/loads.txt, results/stress.txt. In focus: The current folder.octave-cli …/run_analysis.mfullfile(here, 'data', …)fullfile(here, 'results')The current folderany folder, same resultrun_analysis.min project/herefileparts(mfilename(…))data/loads.txtfour loads in kNresults/stress.txtwritten by the script

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. Started from elsewhere. The run starts in some other folder, project/data in the session, and names the script with a path. Relative names such as data/loads.txt would now point to the wrong place.
  2. Where am I?. mfilename('fullpath') returns the script's own path without .m, and fileparts keeps its folder. The script calls that folder here.
  3. Read the data. fullfile(here, 'data', 'loads.txt') builds the path to the data from the script's folder, whatever the current folder is, and load reads the four loads.
  4. Write the results. The results folder is built the same way, created when missing with mkdir, and the stresses are written to results/stress.txt inside the project.
  5. Same output anywhere. Started from project/data or from the folder above the project, the script reads and writes the same files and prints the same line, Wrote 4 stresses.

Here are both scripts started from three places:

One project, three current folders, GNU Octave 11.3.0 Python · project_session.py
from session import run, version

version()
run("""
cd project && octave-cli --no-init-all analysis_fragile.m
!octave-cli --no-init-all project/analysis_fragile.m
octave-cli --no-init-all --eval "run('project/analysis_fragile.m')"
octave-cli --no-init-all project/run_analysis.m
cd project/data && octave-cli --no-init-all ../run_analysis.m
cat project/results/stress.txt
""")

Output

# GNU Octave (aarch64-apple-darwin25.4.0) version 11.3.0
$ cd project && octave-cli --no-init-all analysis_fragile.m
Read 4 loads
$ octave-cli --no-init-all project/analysis_fragile.m
error: load: unable to find file data/loads.txt
error: called from
    project/analysis_fragile.m at line 2 column 1
[exit status 1]
$ octave-cli --no-init-all --eval "run('project/analysis_fragile.m')"
Read 4 loads
$ octave-cli --no-init-all project/run_analysis.m
Wrote 4 stresses to results/stress.txt
$ cd project/data && octave-cli --no-init-all ../run_analysis.m
Wrote 4 stresses to results/stress.txt
$ cat project/results/stress.txt
  10 kN:   88.4 MPa
  15 kN:  132.6 MPa
  20 kN:  176.8 MPa
  40 kN:  353.7 MPa

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 project_session.py

From inside the project, the fragile script read its 4 loads; from the folder above, it stopped with load: unable to find file data/loads.txt and status 1. run('project/analysis_fragile.m') worked, because run changes into the script’s folder, runs it and changes back, as both the Octave manual and MathWorks document. run_analysis.m wrote the same four stresses, from 88.4 to 353.7 MPa, whether it was started from the folder above or from project/data.

Key idea

here = fileparts(mfilename('fullpath')) gives a script its own folder, so every path built with fullfile(here, …) points to the same files whatever the current folder is.

A small research project then needs only a few conventions: scripts at the top of the project folder, inputs in data/, outputs in results/, helper functions in a folder added with addpath at the start of a session, and every path built from here.

cd without a folder differs between the two programs

In Octave, cd alone changes to your home folder; in MATLAB, the Octave manual notes, it prints the current folder. Scripts that build paths from their own location never need cd at all.

Checkpoint

Check: A project that runs from any folder

  1. Question 1 of 2 What does fileparts(mfilename('fullpath')) give inside run_analysis.m?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The folder that holds run_analysis.m, wherever Octave was started

    The script asks where it is, not where you are, so paths built with fullfile(here, …) find the same files from any current folder.

  2. Question 2 of 2 From the folder above the project, octave-cli project/analysis_fragile.m failed, but run('project/analysis_fragile.m') worked. Why?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: run changes into the script's folder, runs it and changes back, so data/loads.txt is found

    With octave-cli the current folder stayed the one above, so data/loads.txt pointed nowhere. run switched to the script's folder for the run, which is why it worked, but only a path built from the script's own folder works however the script is started.

Practise: make a script run from anywhere

Three exercises, on your own computer, with the files of this page:

  1. Save cooling.m, run it by name, then use who to see its variables. Rename it to tea-cooling.m and try to run it by name: what does Octave say?
  2. Save report.m and a script called mean.m in one folder, reproduce the invalid call to script error, and repair it by renaming. Check with which mean before and after.
  3. Copy the project folder with analysis_fragile.m and data/loads.txt. Change the script so that it builds its path from here, as run_analysis.m does, and run it from the project folder, from its data folder and from the folder above. All three runs must print Read 4 loads.

Then test yourself on scripts, name lookup, the search path, file paths and projects. Each question waits for your answer, says at once why it was right or what it missed, and the next one goes where you are least sure:

Practice that adapts to you

Practise this lesson

15 questions about 5 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 15 How do you write a comment that spans several lines and works in MATLAB and Octave?

    Choose one answer.

    Show the answer: Question 1 of 15

    Answer: Put %{ on a line of its own before it and %} on a line of its own after it

    %{ and %} enclose a block comment when each stands alone on its line. Octave also accepts #{ and #}, which MATLAB does not.

  2. Question 2 of 15 You save a script as tea-cooling.m and type tea-cooling at the prompt. What happens?

    Choose one answer.

    Show the answer: Question 2 of 15

    Answer: Octave reads it as tea minus cooling and reports 'tea' undefined

    Name scripts with letters, digits and underscores, such as tea_cooling.m. octave-cli tea-cooling.m would still run the file, but its name could never be typed at the prompt.

  3. Question 3 of 15 You run cooling, then a second script that sets T = 300 for an oven. What is T afterwards?

    Choose one answer.

    Show the answer: Question 3 of 15

    Answer: 300

    Scripts share your workspace, which is why one script can overwrite another's variables. Functions, a later lesson's topic, keep their own.

  4. Question 4 of 15 Which does Octave check first for a name, a variable or a file in the current folder?

    Choose one answer.

    Show the answer: Question 4 of 15

    Answer: A variable

    The search starts with the workspace: a variable hides every function of the same name, in Octave and in MATLAB.

  5. Question 5 of 15 What does Octave 11.3 do with which -all mean?

    Choose one answer.

    Show the answer: Question 5 of 15

    Answer: It warns that -all is not yet implemented and shows only the first match

    In Octave 11.3, which -all gives the first match only, after a warning. MathWorks documents that MATLAB's which -all lists all of them.

  6. Question 6 of 15 You want to save a new script as max.m. What do you check first, and why?

    Choose one answer.

    Show the answer: Question 6 of 15

    Answer: which max, because a name that is already a function would be hidden by your file

    Check a new name with which (or exist) before using it, and choose one that says what the script does, such as max_load_report.m.

  7. Question 7 of 15 Which function removes a folder from the search path?

    Choose one answer.

    Show the answer: Question 7 of 15

    Answer: rmpath

    addpath adds folders, rmpath removes them, and path() returns the whole search path, which path(old) restores.

  8. Question 8 of 15 Why does the lesson advise against savepath for a project's folders?

    Choose one answer.

    Show the answer: Question 8 of 15

    Answer: It writes the path into a startup file, so every later session, of every project, gets those folders

    Set the path where the project needs it, keep a copy with path(), and restore it, so other projects start clean.

  9. Question 9 of 15 Put the lines of a project session in the order that leaves the search path as it found it.

    Give each item its position, from 1 (first).

    Show the answer: Question 9 of 15

    Answer:

    1. old_path = path();
    2. addpath(genpath('tools'))
    3. run the analysis
    4. path(old_path);

    Save the path first, add the folders the work needs, do the work, then put the saved path back, as the session did before exist('kn_to_n') returned 0 again.

  10. Question 10 of 15 According to the Octave manual, what does fullfile put between the parts on Windows?

    Choose one answer.

    Show the answer: Question 10 of 15

    Answer: A backslash

    fullfile picks the separator of the system: \ on Windows, / on macOS and Linux, so one line of code fits all three.

  11. Question 11 of 15 What does this give on macOS?

    Read the code, then choose one answer.

    fullfile('data/', '/raw', 'loads.txt')
    Show the answer: Question 11 of 15

    Answer: ans = data/raw/loads.txt

    The session showed data/raw/loads.txt: fullfile tidies separators, which hand-joined text never does.

  12. Question 12 of 15 A script reads the file whose path is in f and must write summary.txt in the same folder. Which line builds that path on every system?

    Choose one answer.

    Show the answer: Question 12 of 15

    Answer: out = fullfile(fileparts(f), 'summary.txt');

    Split with fileparts, join with fullfile: the result is the input's folder plus the new name, on any system.

  13. Question 13 of 15 Run from the folder above the project, what did analysis_fragile.m print?

    Choose one answer.

    Show the answer: Question 13 of 15

    Answer: error: load: unable to find file data/loads.txt

    A relative path is read from the current folder. From the folder above, data/loads.txt does not exist, so load failed and the run ended with status 1.

  14. Question 14 of 15 Why does run_analysis.m check exist(out_dir, 'dir') before writing?

    Choose one answer.

    Show the answer: Question 14 of 15

    Answer: To create the results folder with mkdir when it is missing

    exist with 'dir' returns 7 for a folder and 0 when there is none, so the script creates results/ the first time and reuses it afterwards.

  15. Question 15 of 15 A script ends with cd, without a folder, to go back where it started. What happens, by the Octave manual?

    Choose one answer.

    Show the answer: Question 15 of 15

    Answer: In Octave it changes to the home folder, and in MATLAB it prints the current folder, so neither goes back

    cd alone goes home in Octave and only prints the folder in MATLAB. A script that builds its paths from its own folder never needs cd, and run changes back by itself.

Interview questions

Warm-up: in what order does Octave look for a function when a script uses a name?

First it checks for a variable of that name, because a variable hides any function. Then it looks for a function in the same file and in a private folder beside it, then for a file in the current folder, then in the other folders of the search path in their order, and the Octave manual places built-in functions after the path. The first match wins, so a mean.m saved in the current folder hides Octave’s own mean, and a variable called sum hides the function sum. which name tells you which one a name refers to right now. MATLAB’s documented order has the same outline: variables first, the current folder before the rest of the path.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    A thesis script runs only when its own folder is the current folder; from anywhere else it cannot find its data. Your supervisor must run it from another folder on a cluster. How do you fix it, and how do you show the fix works?

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    Eight people in a lab share a folder of helper functions on a network drive, and each added it with savepath. After someone edits a helper, results differ between people. Redesign how projects find and pin the helpers.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • A script is a .m file of commands that runs in your workspace, so its variables stay after it ends; % and %{ … %} are portable comments, and %% starts a section.
  • Octave takes the first match for a name: a variable, a function in the same file or a private folder, a file in the current folder, the search path, then the built-in functions, so a stray mean.m hid the function mean.
  • which name shows what a name refers to; in Octave 11.3, which -all gives only the first match.
  • addpath and rmpath change the search path for the session; save path() first and restore it afterwards, and leave savepath alone.
  • fullfile, fileparts and filesep build and split paths for every system, and mfilename('fullpath') with fileparts gives a script its own folder, so a project runs from any current folder.

Terms in this lesson

code section
A part of a script that begins with a line starting with %%. MATLAB's editor can run one section at a time, and Octave's publish uses sections as headings.
function precedence order
The fixed order in which MATLAB and Octave look up a name: variables first, then functions in the same file and private folders, then the current folder and the search path.
script file
A text file of commands ending in .m that runs as if its lines were typed at the prompt, in the same workspace, so its variables remain after it ends.
search path
The list of folders in which MATLAB and Octave look for function and script files. It starts with the current folder; addpath and rmpath change it for the session.

References

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.