How do I make a generic function?
Show older comments
I need to make a function that takes the lowest score out of an array, takes the sum of the rest and averages them, and then creates a vector with each score in it.
The first problem is that I'm struggling to actually create a function. I'm not sure how to begin writing this in MATLAB, and I cannot quite understand the help I find.
Does anyone have any examples of functions and how to create them?
Answers (1)
James Tursa
on 6 Mar 2018
Edited: James Tursa
on 6 Mar 2018
Here is how you start: Use the editor to make a file. Suppose you wanted the function called myfun. Then use the editor to start writing that file:
edit myfun.m
In that file, put the signature of the outputs and inputs like this (here I am assuming three inputs and two outputs ... the names used for these arguments are arbitrary so pick some meaningful names in your real code):
% Some text here to briefly describe the function
% Some more text describing the inputs and outputs
function [out1,out2] = myfun(in1,in2,in3)
% put your code here
end
Push the "disk" button to save the file. Then to use the file, simply call it at the command line or from within a script or function file like this:
A = something;
B = something;
C = something;
[D,E] = myfun(A,B,C);
3 Comments
Tobias
on 15 Feb 2023
Is it necessary to have the function name match the file name or can i have a file with multiple different functions in it?
John D'Errico
on 15 Feb 2023
Edited: John D'Errico
on 15 Feb 2023
You can have multiple functions in one file, but essentially, your code will only see the main function at the top level. The other functions can be seen as sub-functions to the top level function. (Actually, that is not totally true, since you can return function handles, but that is way beyond the scope of this question.)
So no, you cannot have a large mess of functions in one file and have them all directly accessible to all of your code.
Does the function name need to match the file name? If it does not match, then MATLAB will actually use the FILE name. It is far safer and better to have them match though, as confusion will reign supreme otherwise.
Walter Roberson
on 15 Feb 2023
If you want to create a library of functions in the same file then you can create a class in which the functions are marked as static members of the class. Then once the class is loaded, the functions will be visible to matlab.
Categories
Find more on Scripts in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!