0

I am writing a script to access a function that has been written in another script.

When I run the second script the error is that the function is undefined.

I have been working backwards and am currently trying to get the function to work in the command window.

The function file has appeared in the current folder window. When it is highlighted all functions and parameters are displayed in the window below (displays the file name on top then the file contents).

I am still getting a function is undefined when I copy and paste the functions call from the script into the command window.

I tried rebuilding the functions individually in separate scripts, but I am still receiving an error message.

I have made sure the are in the same folder, and are spelled exactly the same, what am I doing wrong?

''' %file name Lab_5_functions.m

    function[vel] = velocity (g,m,co_d,t)
         vel= ((g*m)/co_d)^(1/2)*tanh(((g*co_d)/m)^(1/2)*t);
    end

    function [dvel]= dvelocity (g,m,co_d,t)
         dvel=(((.5*(g*m)/co_d)^(1/2)*tanh(((g*co_d)/m).^(1/2)*t_sec))-(((g*t)/(2*m))*(sech(((g*co_d)./m).^(1/2)*t))));
    end

''' v=velocity(1,2,3,4) %error message below: Undefined function or variable 'velocity'. '''

Thanks -MK

2 Answers2

0

Matlab is searching for functions using filenames. So you define a single public function myfunc in a file myfunc.m.

You can define additional functions in that file, but they will not be accessible outside that .m file.

nimrodm
  • 23,081
  • 7
  • 58
  • 59
0

MATLAB looks for filenames to find the functions and expects the first line of that file to be a function definition.

For example: myfunc.m

function output = myfunc(input)

If you do want many functions in one file (like a module/library), I have used a work-around before: write all your functions in the file, then include an if-else block to call the correct function. Multiple arguments can be parsed with some simple checks (see nargin function). It is a less elegant solution; I only use it if I have many simple functions and it would be plain annoying to have heaps of .m files.

Here is a simple example:

Call the file: myfunc.m

function output = myfunc(fn, arg1, arg2, ...)

    function out = func1(arg1, arg2, ...)
        out = 0

    if strcmp(fn, 'func1')
        if nargin == 2
            output = func1(arg1)
        end

    elseif strcmp(fn, 'func2')
        ...
    end

wgb22
  • 247
  • 1
  • 13