How to organize Matlab code?

Say I have a MATLAB code that uses some functions. I do not want to define functions in the same file as the code that uses the functions.

On the other hand, the decision to make an m file for each function is also not suitable for me, because I do not want many files. I want something like a utils file that contains these functions from which I can import functions like in python, for example.

What would you recommend?

+8
matlab
source share
2 answers

What you most likely want is to use package , which is similar to the python module, as it is a folder where several files can be stored. You do this by putting + at the beginning of the folder name, for example +mypackage . You can then access the functions and classes in the folder using the package.function notation, similar to Python, without polluting the global list of functions (only the package is added to the global list, and not to each of its functions). You can also import individual functions or classes. However, you should always use the full path to the function, there is no such thing as relative paths like in Python.

However, if you really want several functions for each file, perhaps best of all you can create a top-level function that returns a struct for the other functions in the file, and then access the functions from this structure. Since MATLAB does not require the use of () with functions that do not require input, it behaves superficially like a python module (although I do not know how this will affect performance).

I know this is a pain in the neck. There is no reason mathworks cannot allow the use of files in the form of packages that they currently make for folders, for example by putting + at the beginning of the file name. But they do not.

+12
source share

A solution close to what you are looking for could be using classes. The class contains methods that can be public (visible from the outside) or private (visible only from the inside). Implementations of class methods can be either in multiple files or in the same file.

Here is a simplified example

 classdef Class1 methods (Static) function Hello disp('hello'); end function x = Add(a,b) x = Class1.AddInternal(a,b); end end methods (Static, Access=private) function x = AddInternal(a,b) x = a+ b; end end end 

Example usage -:

 >> Class1.Hello hello >> Class1.Add(1,2) ans = 3 >> Class1.AddInternal(2,3) Error using Class1.AddInternal Cannot access method 'AddInternal' in class 'Class1'. 
+2
source share

All Articles