Momen Zalabany
Momen Zalabany

Reputation: 9007

Create functions in matlab

How can I create a function with MATLAB so I can call it any where in my code?

I'm new to MATLAB so I will write a PHP example of the code I want to write in MATLAB!

    Function newmatlab(n){
    n=n+1;
    return n;
    }
array=array('1','2','3','4');
foreach($array as $x){
$result[]=newmatlab($x);
}
print_f($result);

So in nutshell, I need to loop an array and apply a function to each item in this array.

Can some one show me the above function written in MATLAB so I can understand better?

Note: I need this because I wrote a code that analyzes a video file and then plots data on a graph. I then and save this graph into Excel and jpg. My problem is that I have more than 200 video to analyze, so I need to automate this code to loop inside folders and analyze each *.avi file inside and etc.

Upvotes: 0

Views: 2125

Answers (1)

dantswain
dantswain

Reputation: 5467

As others have said, the documentation covers this pretty thoroughly, but perhaps we can help you understand.

There are a handful of ways that you can define functions in Matlab, but probably the most useful for you to get started is to define one in an m-file. I'll use your example code. You can do this by creating a file called newmatlab.m in your project's directory that looks something like this

% newmatlab.m
function result = newmatlab(array)
result = array + 1

Note that the function has the same name as the file and that there is no explicit return statement - it figures that out by what you've named the output parameter(s) (result in this case).

Then, in the same directory, you can create a script (or another function) that calls your newmatlab function by that name:

% main.m (or whatever)
a = [1 2 3 4];
b = newmatlab(a)

That's it! This is a simplified explanation, but hopefully enough to get you started and then the documentation can help more.

PS: There's no "include" in Matlab; any functions that are defined in m-files in the current path are visible. You can find out what's in the path by using the path command. Roughly, it's going to consist of

  1. Matlab's own directory
  2. The MATLAB subdirectory of your Documents directory
  3. The current working directory

Upvotes: 1

Related Questions