Learn how to create a simple script, define some variables, and transpose a matrix, and see how to suppress script output in the Command window.
- [Instructor] So working in the command line is great, but if we want to do any heavy lifting, we need to be able to create scripts. Scripts are just series of commands that we save in a text file and MATLAB will run them sequentially. There's a couple different ways to create a script. Let's go ahead over to our current folder here. Right-click, say new file, and script. Scripts have the .m extension, and we'll just call this one MyFirstScript. We could double click on it here, or we can also go into the command window and hit edit, and my and I'll tab complete myFirstScript.
And it opens up a text editor with our empty script in it. Keep in mind these are just text files so you could edit them in something like Sublime Text outside of MATLAB if you wanted to. So in our script, we can do things like add a comment. The comment indicator in MATLAB is the percentage sign. So we can say my first script, I'm so excited. We can also send texts to the command line if we want. The dsp command, so we'll display something and we want it to be a string.
Say go go gadget script. And if we run this script here, we'll see in the command line it says my first script being run and we see our display, go go gadget script. All right, we're lookin' good. So let's create a variable in our script here. Let's make a matrix called myMat. And why don't we just create a matrix full of random values? How about some random integers? I'll use the randi for random integers.
And let's make a three by three matrix. If we run this without the semicolon, we'll see our matrix in the command window down here. I'm just going to drag that up a bit. And if we go ahead and clear the screen, clc, keep in mind you can always put a semicolon after the line to suppress the output. Now if we run it, and we'll see the output without all of the numerical mess. So now that we've created a variable, we see that it's in the workspace, myMat. So why don't we go ahead and create its transpose as well? Let's call it myMatTranspose.
Keep in mind a transpose is when we swap the rows and columns of a matrix. So MATLAB has a real handy way to transpose a matrix, since we do it so often. And it's just by putting a single quote after your matrix variable. And we'll add a semicolon to suppress the output there. And let's go ahead and run our script. So we can see, we've got myMat and myMatTranspose, created up here in the workspace. And we can always inspect them down in the command window as well. If I do myM, tab complete and select myMatTranspose.
We can see it displayed here in the command window.
- 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