Functions with Multiple Inputs or Outputs
From the series: Managing Code in MATLAB
Learn how to create MATLAB functions with multiple inputs and outputs.
Published: 12 Nov 2020
Hello, this is Doug at the MathWorks bringing your video 248 about having multiple inputs and multiple outputs in a function. I'm going to start with a function that was already built that has one input and one output. And I'm going to convert this to support multiple inputs and multiple outputs. It really doesn't matter what the function does so much as that it is a function.
So I see here that, as soon as I go into this function, I set a variable number of terms for the Taylor series approximation. That's what we call hard coded. And maybe we want that to be a variable so that we can get more or less precision. So I'm going to change this to num terms, like this. And now we don't need to specify that right there.
And one test of this-- let's try this. And I'm going to go to the command window. Taylor sign of 0.5, and it says we didn't ask for enough terms. There we go. And let's say we want to have multiple outputs of this. Well, why don't we figure out what the error is? So I'm going to put some brackets around here, showing that we have multiple outputs coming.
And the way this is usually done is you put the most important output first. That way, if the user calls it and doesn't ask for both outputs, only the first one will be given. In this case, we usually want the approximation. But we might not always want the error. And so down here at the end-- let's make some room for it-- error is equal to sine of x minus the approximation.
So if we go back to the command window, we haven't asked for the second output. So it doesn't really change. However, if we say approx and error, like this, now we're getting them both and we can see what our error is in this little function. Something that people like to do in situations like this is put in some default values for number of terms. So if nargin, number of arguments in, equals one-- then we're going to say num terms is equal to some default value.
If we save that and go back to the command window, it doesn't change anything here. But if we don't give a second argument, it's still going to work. And of course, let's change the number of terms. And we can see the error gets much bigger or smaller as we change that. Thank you.
Sie können auch eine Website aus der folgenden Liste auswählen:
So erhalten Sie die bestmögliche Leistung auf der Website
Wählen Sie für die bestmögliche Website-Leistung die Website für China (auf Chinesisch oder Englisch). Andere landesspezifische Websites von MathWorks sind für Besuche von Ihrem Standort aus nicht optimiert.