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

后端 未结 3 1402
孤独总比滥情好
孤独总比滥情好 2020-12-06 15:18

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

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

However, Matlab not

3条回答
  •  甜味超标
    2020-12-06 15:50

    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.

提交回复
热议问题