B Seven
B Seven

Reputation: 45943

How to check if a variable is defined in Octave?

When writing a script that loads data, it's a waste of time to wait for it to load each time.

How to check to see if the variable is defined?

Upvotes: 8

Views: 16209

Answers (3)

Jomoos
Jomoos

Reputation: 13083

You can use the exist function in Octave to do the work. It can be used to check the existence of given name as a variable, built in function, file, or directory. In you case, to check the existence of a variable, you may use something like this:

if (exist("your_var_name", "var") == 1)
    printf("varname exists");
else
    printf("varname not exists");
endif

You may refer the following links for detailed information:

Upvotes: 13

skdev75
skdev75

Reputation: 740

if (exist("itemcount") == 1)
  % here it checks if itemcount is a variable, by changing the value after ==, you can check for function name, file name, dir, path etc.
end

Note itemcount is in double quotes.

By changing the value after ==, you can check for function name, file name, dir, path etc.

from / more info at: https://www.gnu.org/software/octave/doc/interpreter/Status-of-Variables.html#XREFexist

other return values .. 2 if the name is an absolute file name, an ordinary file in Octave’s path, or (after appending ‘.m’) a function file in Octave’s path, 3 if the name is a ‘.oct’ or ‘.mex’ file in Octave’s path, 5 if the name is a built-in function, 7 if the name is a directory, or 103 if the name is a function not associated with a file (entered on the command line). Otherwise, return 0.

Upvotes: 2

charles.fox
charles.fox

Reputation: 493

Need to put the variable name in quotes too,

exist("varname", "var")

Upvotes: 6

Related Questions