Search code examples
matlabstartup

Variable declaration in startup.m not working in MATLAB


I'm trying to declare some magic number constants which I need to access in every script. I made a file load_constants.m in my_path which looks like:

magic_number = 10;
other_magic_number = 12;

My startup.m looks like this:

% add a bunch of packages
addpath ~/Documents/MATLAB/some-package

userpath(my_path)
load_constants

But when I try to access magic_number in the Command Window:

Undefined function or variable 'magic_number'.

Directly declaring the variables in startup.m doesn't work either. How to fix this?


Solution

  • This is normal behavior, startup.m is a function and variables declare inside the function are local to that function (and then vanish when going out of the scope):

    function [] = startup()
    %[
        magic_number = 10; %% This is local variable
    %]
    

    Use the assignin function to have magic_number to be visible from the base workspace:

    function [] = startup()
    %[
        assignin('base', 'magic_number', 10); % This value will be visible from 'base' workspace
    %]
    

    Note that for having magic_number value visible not only to scripts but functions also, it may better to create a magic_number.m function and add it to your path:

    function [v] = magic_number()
    %[
        v = 10;
    %]
    

    which can be called without the brackets (i.e. just like the syntax for variables)