Join Patrick Royal for an in-depth discussion in this video Using built-in functions and variables, part of Learning MATLAB.
In this video, let's take a look at functions in MATLAB. Basically, a function differs from a script in that it has a fixed input and output channels. This makes functions extremely useful for when you're writing complicated programs that might repeat the same calculations over and over again. Rather than rewriting your code, you can simply pull out that part of it into a separate function. MATLAB ships with a wide variety of functions already implemented. So we'll start by going over how to use those. Perhaps the most commonly used functions are matrix generation functions which are used to create a matrix with certain starter data.
As an example, let's type in a equals ones 2,3 in the command Window. This tells MATLAB to generate a new matrix with two rows and three columns and then set all of the values in that matrix to ones. The zeros function does the same thing with zeros, the rand function does the same thing with random numbers and so on. The important thing to note here is that all of these functions use the same syntax. Type in the function name followed by parenthesis containing each of the inputs of the function seperated by commas. Defining every function in MATLAB is beyond the scale of this video but there are several resources that can be used to find and use new functions. If you know what you want to do but you don't know what function to use, then you can go to the official MATLAB documentation site, mathworks.com/help/matlab, and search the documentation for your queries. For instance, if I wanted to learn how to invert a matrix, I could search matrix inverse and the first result would tell me to use the inv function. If you know the name of a function in MATLAB but you are not sure about the order or the nature of the inputs, the best way to find out is to type Help followed by the function name in the command Window. This will return the description of all the different ways the function could be used as well as links to similar functions.
For instance, typing help, zeroes, tells us all the different sets of input that we could give the function, and what results each one will return. It also tells us that we might want to check out the I and ones functions, which are also used to generate simple matrices.
- Installing MATLAB
- Working with MATLAB variables
- Working with matrix and scalar operations
- Creating functions
- Understanding performance considerations
- Building basic plots
- Creating responsive programs
- Editing variables manually
- Working with the Statistics Toolbox