You can also create functions with input arguments that return values.
- [Instructor] Eventually your MATLAB projects, are going to get complicated enough, that you'll want to write your own functions. So, let's take a look at how to do that. I'm going to go into our current folder, right click, save new file, and function. I'll call it, my func, and let's go ahead and open that up. So we see that MATLAB has created, a boilerplate function for us, and the syntax is pretty straight forward. We define it as a function. METLAB has given us two generic output arguments, ouputArg1, and outputArg2.
Those always need to be enclosed, in square braces ([ ]). And that's equal to the name of our function, and some generic input arguments. So let's make our function do something fun. How 'about we'll pass it A and B and have it calculate C, from the Pythagorean Theorem. I'm going to just head down here to the command window, and clear that real quick so that it's nice and clean. And so for out output argument, we want it to give us C, and for our input arguments we'll pass it A and B, because everybody loves some A squared plus B squared, equals C squared.
So we can see here MyFunc and it gives us summary, of the function goes here, and a detailed explanation goes here. So, this is what will come up if we ask, for the help for our function. So, let's say calculate from Pythagoras, and a detailed explanation goes here. Let's say, I love right triangles, go ahead and save that, and we can get rid of, our second output argument, we don't need that there.
So, let's change our first output argument, to C, and we want C to be equal to the square root, so we can do sqrt, which is MATLAB square root function, of and then A squared, plus B squared. Now I don't know about you, but I am paranoid, about orders of operations, 'cause I've been bitten by that, in the past, so I'm just going to make sure that METLAB, is going to do some A squared and B squared first, before adding those numbers up, and that looks pretty good.
So, I'm going to go ahead and save this, and let's head down here to the command window, and first let's see if we can see our help. So, I'm going to type help, my func, and we see, aha, we calculated C from Pythagoras, and I love right triangles. So, it's always good to put some useful text in there, even though the text we put in isn't particularly useful. And let's go ahead and calculate something here. So I'm going to say hyp for hypotonus, equals my func, and what should we pass it? Let's do three and four and see, if we get our perfect right triangle, nice! Hyp equals five.
So this is how you create a function in MATLAB. It can come in real handy, when you're simplifying your code in the future.
- Creating MATLAB variables
- Working with matrix and scalar operations
- Using if statements and loops
- Creating functions
- Importing data
- Building basic plots and 3D plots
- Working with images
- Creating Simulink models