Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I break up my Matlab code into functions without creating many files?

I tried coding up a function in a Matlab .m file:

function returnValue = someFunction(x, y)
returnValue = x * y + 3
end

However, Matlab noted that I was not allowed to simply declare a function in the middle of my script. I tried moving the function to the top of the file, but Matlab forced me to rename my function to the name of the file.

I soon realized that Matlab functions must match the name of their files. How do I modularize my Matlab code within a single file? Is there a way I could just define a function in the middle of my script?

like image 219
dangerChihuahua007 Avatar asked Sep 18 '25 13:09

dangerChihuahua007


1 Answers

Anonymous functions

For very small functions like the one in your example, you could simply define an anonymous function like this: f = @(x, y) x * y + 3. You can define such functions even in the prompt of your workspace or in any script file.

Nested functions

If you turn your MATLAB script into a function, it will allow you to define nested functions:

function a = my_script(x)
  y = 3; 
  function r = some_function(b)
    r = b * y + 3;
  end
  a = some_function(x)
end

Note that the nested function can see the value of y. This can be handy for example, when you optimize parameters of an ODE and the solver you use doesn't provide a means to modify parameter values.

Sub functions

You can also define a function with multiple local sub functions in one single file. Sub functions are defined below the "public" function. In your example some_function could be a sub function in my_script.m.

function a = my_script(x)
  y = 3;
  p = 42;
  a = some_function(x, y) + p;
end

function r = some_function(x, y)
  r = x * y + 3;
end

The end keywords are optional here. In contrast to nested functions, sub functions are rather helpful to encapsulate pieces of an algorithm, as some_function will not see the value of p.

like image 179
s.bandara Avatar answered Sep 21 '25 05:09

s.bandara