Is there a way to define functions inside of sections of a MATLAB file that you can call from the command window? I have three functions I want to define in a single .m file (each in its own section) but I don't see how I will be able to call them.
            Asked
            
        
        
            Active
            
        
            Viewed 200 times
        
    0
            
            
         
    
    
        David Maust
        
- 8,080
- 3
- 32
- 36
 
    
    
        Ryan
        
- 7,621
- 5
- 18
- 31
- 
                    2See also [How can I break up my Matlab code into functions without creating many files?](http://stackoverflow.com/q/18796978/2778484). – chappjc Feb 20 '14 at 20:59
3 Answers
0
            
            
        You can do one thing. Create folder myFuncitions and append plus sign in front of folder name like "+myFunctions" and move all your functions .m file in that folder. You can access functions: myFunction.Func1(), muFunctions.Func2(), and so on...
 
    
    
        User1551892
        
- 3,236
- 8
- 32
- 52
0
            
            
        Using class is your best bet. In class, you can define multiple methods (i.e. function) and call them independently of their order.
For example:
classdef Cat < handle
    properties
        meowCount = 0; 
    end
    methods 
        function obj = Cat()
            % all initializations, calls to base class, etc. here,
        end
        function Meow1(obj)
            disp('meowww'); 
            obj.meowCount = obj.meowCount + 1;
        end
        function Meow2(obj)
            disp('meowww meowww'); 
            obj.meowCount = obj.meowCount + 2;
        end
    end    
end
Demonstration:
>> C = Cat;
>> C.Meow1; 
meowww
>> C.meowCount
1
>> C.Meow2
meowww meowww
>> C.meowCount
3
 
    
    
        m_power
        
- 3,156
- 5
- 33
- 54
0
            
            
        Is it possible to define more than one function per file in MATLAB, and access them from outside that file? gives a good answer. Sample code to implement it is
function fHandle=temp(fnum)
switch fnum
  case 1, fHandle=@func1;
  case 2, fHandle=@func2;
  case 3, fHandle=@func3;
end
end
function y=func1(x)
y=x+1;
end
function y=func2(x)
y=x+2;
end
function y=func3(x)
y=x+3;
end
From the command line type
f1=temp(1);f2=temp(2);f3=temp(3);
then [f1(1) f2(1) f3(1)]
gives
ans = 2 3 4
 
    
    
        Community
        
- 1
- 1
 
    
    
        Joe Serrano
        
- 424
- 2
- 7