Learn MATLAB from Phil Parisi. Phil is a PhD engineering student and his teaching style is clear and to the point. MATLAB is a programming language and software suite used for data analysis, scientific computing, and visualizations. And it's widely used in academia and industry. Hey there YouTube, we are going zero to hero today in MATLAB.
Thanks for joining me, we're going to jump right in. Right in front of us is the first screen you'll see when you open up MATLAB for the first time. This is called the MATLAB IDE, Integrated Developing Environment. This is the place that we do all of our programming in MATLAB. Center of the screen, we have the command window.
This essentially serves as a powerful calculator. Let's type some stuff in here. Let's just do 7 plus 8, or 9. That gives us 16. We can do 10 minus 5. That gives us 5. How about the square root of 225? 15. What about square root of 15 times 9?
34.8569. Right, these are just quick in and out commands to give us information. Now if you look on the right, we've already got something popping up in our workspace.
We've got something called ants. And if you see after every time we run a command, we're getting this output ants. which is short for answer and it equals the value of the previous statement that we entered in. Ants is our first variable that we've created. If I just ask MATLAB for the value of ants, it'll spit it right back out to me as the most recent answer that was spat out.
If I were to do this again and say eight plus two ants is now 10 you can see the workspace variable has been updated to 10 and I can ask for ants and it's 10. I can also do ANS plus nine and we'll get 19. MATLAB is holding this ANS variable in memory. We're getting kind of clogged up here to clear the command window. CLC and hit enter and that'll remove all that crap in the command window.
All of our previous statements are now gone, but they were executed, which is why ANS still holds its value right here. ants still equals 19 even though we just cleared away the lettering with clc. If you want to actually clear the workspace variables you'll need to use the command clear vars. This is one word.
You hit that, boom, now there's nothing in our workspace and if I ask for ants I get nothing out because ants doesn't exist right now. Let's try creating some more variables with actual nice names that we can use. such as x equals 10 and y equals 20. Here in our workspace we now have two variables x and y with values 10 and 20 and we can use those variables to do further mathematics.
Here we've used x plus y equals 30 and 30 is saved to our ans variable. Of course we can ask MATLAB for just the x value and just the y value that we created. CLC to free up our command window.
There's another cool way to see our workspace variables, and that's by typing whose. Just type that, and we'll see the names of our variables that exist here. Notably, this column, the class column, will describe what type of variable these are.
In many programming languages, handling the types of variables are very important. Luckily in MATLAB, 95% of the time we're only going to be dealing with doubles. Double is just the way that MATLAB holds the data that belongs to x, y, and all the other variables that we create. This is a nice bridge into other types of variables such as strings. Let's call w equals the word new.
No problem. This isn't a number, right? This is the word new and if we type whose we'll see that MATLAB has now created w as a char. This is short for character. Characters in MATLAB are defined when we use single apostrophes around a string of letters or numbers.
If I do two apostrophes, such as z equals york, with double apostrophes on either side, and I do whose, now we're seeing w is still a char and z is now a string. These three Chars, doubles, and strings will cover almost anything you need to do for basic MATLAB. And we're not going to go any further beyond the data type discussion for now. Let's clear our workspace and start fresh.
One thing you may have noticed when we define these variables, every time we hit enter MATLAB provides an output here. If we don't want that output, we can simply add a semicolon at the end of the sentence. like this. These semicolons are called suppression. They prevent MATLAB from outputting a line of code.
MATLAB still runs that. Everything we do in this before the semicolon MATLAB still acts on. For example, if we define x equals x plus 7, we run this.
This line is still run, but we just don't see an output. By the way, you'll notice that our x variable is now 26. Why is that? The programming language moves sequentially.
In this line, x was defined as 19. When we run this line, x right here is replaced with 19, add 7 to 19, and you get 26 on the right-hand side of this equation. That value is stored to x. If we ask for x out, x is now 26. Another piece of useful punctuation is the comma.
Let's say you want to add multiple things on one line. I'm clearing out everything right now. Let's say you want to do define u is 25 and then me is 10. If I run this I can now act two things on one line.
Two commands for one line. They both output here. If you didn't want them to output, what would you do?
You'd add semicolons at the ends of these lines. In fact, at the end of each expression. So after 25 and after 10. Briefly, hit the up arrow in your keyboard and you're going to see that you can access all the old commands that you were using.
I'll bring this one back, add a semicolon here and a semicolon here. And we'll see no output, but these two lines are both run. We've seen a few popular operators. I can do u plus me, I can do u minus me, I can do u divided by me, u times me, u to the power of me, use that caret on your keyboard to do the power, and we've seen square root as well.
Square root of u is 5. One thing to note, You can do compound expressions. If I do the square root of 8 times 9, that's going to give me the correct answer. The same as the square root if I defined x as 8 times 9 and then did square root of x. These two expressions are essentially the same thing.
x is just holding 8 times 9 and we're plugging it in here, whereas here we're just putting 8 times 9 in directly. But it's the same thing mathematically, and you can see we get the same answer out in both cases. Again, you can always check to see what variables exist if you use the WHOSE command, and they're all displayed here.
That covers how our workspace works on the right. If you want to view these variables in further detail, you can always double click on them. This will be useful when we have matrices and things like that, that are not just a single number in a corner. Other aspects of the MATLAB IDE, on the left we have the current folder. This should be the place that you're actively working in and saving your MATLAB scripts to.
This will be more important later. The toolbar is up top. This is where you can create new scripts and files, open things, import data.
You know, it's kind of just your overseeing software component of the actual MATLAB You might be envious of the dark mode I've got going on. If you want to also change that, go to your preferences, go to colors, and this screen should show up. Uncheck the use system colors box, set your background color to black, and your text to white.
You can also copy all the remaining colors that I've got set up here. It's up to you though what your color preference is. I like high contrast.
This is also a great place if you're looking to modify other things in your editor and debugger, you want to change the font sizes, things like that, you can all do it from this preferences tab. You've seen so far that MATLAB can act as essentially a calculator on steroids, but it's not very useful if we're just typing line by line and having to use the outputs that we create. Let's create a new script. To do this, you can click the New Script button in the very top left, or click New and then Script. These are very powerful, and you're going to do the majority of your programming in these scripts.
The power of them is that you can type multiple lines of code without anything happening to the MATLAB command window. You can see I typed clear vars, but yet the workspace hasn't been cleared. And that's just because I've typed these, but I have not run these commands yet. To do an actual running of your script, you have to click the run button. Save and run.
We need to save this file. I'll just call it... Basics we run it and now look our command window is giving us the output of x equals 10 Which was the result of this line also it cleared all the previous stuff We had in our command window, and we cleared all the variables so now we only had x after we created it This is the real way We're going to code in this beginner course and the way that you should structure all your programs from here on out You can do things like x equals x plus 7, add in w equals x plus y, suppress those, run this, and we'll get no output because we suppressed every single line of code. But w, x, and y all exist in the workspace because we ran these lines and they were all assigned during this process. If we wanted to see a variable, we can check in the command window or When you run this script, you can just ask for that variable to be outputted.
And there we run it again and you get w equals 27. I'm running this the cheating way. I love doing it. Control and enter is the quick way to run your MATLAB scripts. You can always use this run button at the top as well.
Let's clear out our script and our workspace using clc and clearvars and start fresh here for a new topic. vectors and matrices. Let's add a heading for our script, and you can do that using the percent sign.
Yes, it's percent, I know it's weird, but it's MATLAB standard for adding comments. Comments are very useful. You can add them all over your scripts so that you know what values you're defining and why. Very often, we know why we're doing stuff in the moment, but many, many days later, even minutes later, you're going to come back and wonder why you needed to do something. You can add comments on whole new lines like this.
You can also add comments inline like this. New line and inline comments. And then when you run your script using control and enter, you'll see that the lines, these comments, aren't even included. MATLAB still goes through and creates the variables as such.
This section we'll call matrices and vectors. You're in the matrix laboratory. I hope you know some linear algebra and some basic matrix operations. If not, stay tuned.
We're gonna learn them. First things first, let's always start off our script by clearing our command window and doing a clear vars operation. That ensures that every time we run this script, we're going to have a fresh output. Anything that was previously outputted will be cleaned out. and we're always going to have any new outputs that we call fresh in the command window.
And then clear vars will always wipe away the stuff from our last script and allow us to define new variables that will be available in the workspace at the end of the script. This is good form for our first vector, and vectors and arrays are going to be used interchangeably. Let's say x equals 1 through 10. I typed a colon when I said the word through.
If we run this with control enter, here x is defined as 1, 2, 3, all the way to 10. It's not just a single value anymore, x is a vector or an array. Even in the workspace we see here it's defined as such holding these 10 values. Let's type whose in the command window and we'll see that X is still stored as a double, but it's a 1 by 10 in size. This is because MATLAB uses the standard in linear algebra to do one row by ten columns. This is a horizontal array.
It's one row of values, ten columns across. If you want to switch this, I could do x transpose. Transpose is just a single apostrophe. I run this, and now we see the answer out is a vertical array.
x started out as horizontal. I took the transpose and ans is now a vertical array. We take a look in our command window.
Ans is a 10 by 1. It's 10 rows by 1 column. x is 1 row by 10 columns. Very important to keep this straight as you know.
We can also define arrays and vectors using the linspace function. x equals linspace, and the arguments here are going to be the value you want to start with, and then the value you want to end with. If we run this, oh my gosh, we have a ton of stuff in our output. It's because linspace will automatically generate 100 values between 20 and 50. And that's what we're seeing here. And these are evenly spaced values.
If I did from 0 to 100, We're seeing 100 at the end and we start at 0. You can add one more argument to linspace and that will be the number of terms you want. The default is 100 evenly spaced terms, but if I ask for 101 for example, now I get even numbers here because 100 and 0 are included in these 101 values. I can also do 20 and now we're only a one row by 20 values. a 1 by 20 double as our workspace tells us. Linspace is the first function we've encountered and we'll cover functions extensively throughout this training.
When you have a function, this is a built-in tool that MATLAB has for us to use freely. You're going to always open up functions with parentheses and functions take arguments. These are the values that are inputted to tell the function what to do.
Here our first argument was zero. Our second argument was 100 and our third argument was 20. Each argument is separated by a comma. Note that MATLAB doesn't care if you have spaces or things in between as long as you have commas separating your arguments.
No difference in the output. Another way to define arrays and vectors is simply to do it manually. To do this, you start by opening a bracket and then you type the values you want.
Let's say 12, 50, negative 8, negative 100. Close the bracket and run this. There's y, 12, 50, negative 8, 100, just as we specified here. The only separator I'm using is a space. You can add different spaces in here, run it, and MATLAB won't care at all. It'll give you the same output.
I'm going to suppress these outputs for now as well. The important thing is that there is at least one space between. You can also separate these with commas or no comma.
Run this. Still the same output. Nothing's changed here.
So commas or spaces to separate values in an array or vector. Let's call our first matrix A and we'll define it as a 2x2. We'll call the first row 1 and 3. separated by just a space, and to do a new row you have to use a semicolon, and then 2 and negative 10 will be our third and fourth values. If I run this, here's a 1, 3, 2, and negative 10 ordered, as we discussed, because I have this semicolon here.
I could also add optionally commas between those values and we'll get the same output. If I want to add another row, no problem. 88 and 99. We run that and we added a third row here.
MATLAB will follow every single rule of linear algebra and it assumes you want to do linear algebra throughout your mathematics. For example, if I want to add a value to a it'll follow the linear algebra rule which is add that scalar value to each of the positions In the matrix 99 plus two is 101. Same thing with multiplication. A times 8. Every single value will be multiplied by 8. What happens if I do A times A?
We run this and we've gotten our first error in MATLAB. Just grow to love these errors, but they're trying to help you. It's going to be frustrating when you get them read these errors extensively.
You'll see here Incorrect dimensions for matrix multiplication. Ah, okay. A is a 3 row by 2 column matrix. Linear algebra rules state that we cannot multiply a 3 by 2 by a 3 by 2. That inner dimension has to match.
What we could do is take the transpose of A and do this. A is a 3 by 2, but A transpose is a 2 by 3. right here. Two rows by three columns, and thus when we do this multiplication, it works out.
It follows the rules of linear algebra. But what if you don't want to follow those rules? Let's say you've got x equals linspace 0 to 100. You've got your 100 evenly spaced values, and you want to take, I don't know, the square of x.
So you want to do x squared. Well MATLAB's going to throw you for an error once again. Because this is a 1 by 100 matrix, and you can't multiply a 1 by 100 by a 1 by 100. But what if you just wanted the square of every value?
You wanted 0 squared, 1 squared, 2 squared. To do element-wise operations, that's the difference here. You can do matrix operations, or you can do element-wise operations.
Element-wise operations need a dot in front of them. It's going to be weird to get used to, I know, but the dot is exactly what you need. If I run this, it goes through x and takes every value squared. It's not the best example. Let me just add 101 here so we get even values.
And now you'll recognize this is 0 squared, 1 squared, 2 squared, 3 squared, 4 squared, right all the way down. We should get 100 squared to get 10,000. Remember, arrays and vectors are simply along one dimension, like x equals 22 to 100. Along one dimension, matrices are along two dimensions. There's a few more handy ways to define common types of matrices. If you want to make a matrix of all zeros, you'll do ones and then add an argument This creates a 3x3 matrix of ones.
Very simple. If you wanted to change those dimensions, you could do something like this, and it gives you purely a 3 row by 1 column array of ones. If I wanted to do b as all zeros, I'd do zeros. Let's give it the argument of 10. It gives me a 10x10 matrix here.
You can always check that in your workspace too. Similarly, if I wanted just to do a 2x8... Matrix of zeros, here's two rows by eight. And the last one that we'll cover briefly is going to be the identity matrix. You'll use I, I, just like the eyeball in your face, I of three, and we'll get an identity matrix, which is just ones on the diagonal.
Again, can I add B and C together? Of course not. The matrix dimensions must agree, and MATLAB will continually remind you of that. I can add c and c together, that's not a problem, same dimensions, and I'll get twos along the diagonal because of the summation.
A cool trick here as well, when I had x was 1 to 10, there's actually one more argument that we can add here, and it's going to be this value between the colons. If I do this, we get what we've been expecting, 1 to 10. But think of this as start at 1, jump by 1 value, end at 10. If I wanted to jump every two values, run this and I get 1 plus 2 is 3 plus 2 is 5 plus 2 is 7 plus 2 is 9. If I added another 2, I'd be beyond our upper limit and thus it stops at 9 and doesn't go to 10. Kind of handy if you ever need to jump values quickly. Let's clear everything out and start fresh here. An important part of working with our matrices will be grabbing certain values out of those matrices to use them for further calculations.
Let's start for another example here. Basic A 5 3 4.2. It's going to be a that's a one row. Let's do 8 9 and 0 as our second row.
Easy. Good start. Let's say I want to grab out one of those values.
How about this 9? How would I do that? We can use something called the index. The index goes through a matrix or array or any variable and pulls out elements of those variables.
Here a is a combination of all these individual elements including 9. To use the index you're going to have to use parentheses. Then within those parentheses, you specify the location of the element that you want. Here it's 9. I'm going to call a second row second column, and our output is 9. If I want to access that zero, that's in the second row third column. Let's say I want to add that zero to that nine. Just like this, we're specifying this value, second row third column, which is 0, and we're adding it to the second row second column value of 9. If you just have an array, say a was only this, it's just a simple 1 by 3 matrix.
To grab a value out of that, you can just specify a single number. So A1 would be 5, A2 would be 3, and A3 would be 4.2. This is going to be very frustrating for programmers of other languages because MATLAB uses something called one indexing. That means that in the memory, MATLAB stores the first value of something as the first index.
This is because of the nature of doing matrix. algebra. Linear algebra needs this to be in the first spot. There is no such thing as a of zero.
Array indices must be positive integers or logical values. Final note on this, you can also use end as an index. That'll grab you the last value in a matrix.
This is convenient for let's say you've got a equals linspace you know, I don't know, 220 to 900, and then you've got b equals 1 by every 5 to 98, 980, like this, and you want to find the last value of these. Well, I could tell you right now, linspace has 100 values in it, but for b, I have no idea how many values are in this, so I can just call b end, and I'll get the last value out of b. From there you can work your way backwards if you want. You can call b end minus 10. It'll go back 10 spots.
Okay this isn't b end quantity minus 10. This is go to the last index and then pull back 10 spots. So if we open up b here, go to the end of b, 976, and go 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. 926. That's what we got right here. Very different from b and n parentheses here, which grabs 976 and then subtract 10, which is simply 976 minus 10, which gives us 966. Important differentiation there. We will use these indices further when we get into loops.
The last thing I want to note on it. is that we can use these indices to change values of our matrices. I've just got another very basic array set up here, and I want to do this one value. I want to change it to 100. Let's say it was a typo or something.
I can do a 1 comma 1 and then set that value equal to 100. I'm going to output a afterwards, and we'll see that I've now corrected this value. the first row and first column value to 100. And we see it here in our command window. You can also pull out entire rows and entire columns. I've only shown you how to do this with single stuff right now, like asking for the first row second value of 2. Let's say I want the entire second row here to be outputted.
You're going to use that colon again. What you'll do is you need to determine what you want. So here we want the entire second row.
So that means that we want the second row And instead of specifying a single value, I'll just say give me them all, and the colon will give you them all. Boom. You can also think of this as giving you the first value through the third value. This is the second row first column, second row second column, second row third column, and one to three just gives us the one, two, and three.
If you want just the second row, first and second values, the 5 and the 4, there you go. And if you ever wanted everything, you could just do 1 to end, in case you didn't know what the end of this matrix actually was. Short and sweet, we're moving along well, let's keep going. Let's take a look at a real-world problem that you're likely going to be solving.
What is the maximum value of the following equation on the range 0 to 5? We have the expression for y here. What is the minimum of that function?
What is the x value where the maximum occurs? And then part d is what is y if we input 20.7 for x? This is exactly the type of problem you guys are going to see in the real world. Let's go through step by step. But you need to unthink how you typically solve these problems.
If you just had pen and paper, you'd take the derivative of y, you'd set it equal to zero, and then you'd find what points are the maximum and minima, right? Typical, very standard approach. However, we have a computer.
We have processing power. We can calculate a bunch of different things. So rather than solving this for one x value, what we're actually going to do is generate x values from zero to five.
and then calculate a bunch of y values that correlate to those x values, and then we'll just pick out the largest y value and pick out the minimum of the y values. And then part c and d we'll have to learn some more stuff as we go, but no problem, your brain is pudding right now because you are learning so much. Let's get back into MATLAB. Here we are with a fresh slate. As I mentioned, let's first generate a bunch of values between 0 and 5. I'm using linspace so that'll give us 100. Then at each of those x values, let's calculate a y value.
And let's start easy here, because it's very easy to get lost when you're writing these equations. We want to do x minus 3 per the equation. And let's just run this for now.
Let's make sure that as we progress and add terms, we're not getting errors. This works. We've now calculated what x minus 3 is.
And this is element-wise stuff. x is technically a vector, it's a 1 by 100 vector, and so is y right now. 1 by 100 because every value in x is just being subtracted by 3 right now. Let's take the opposite of that per the equation, and now we need to multiply this to the second power, squared.
If we run this, we're going to get an error. Why? Because this quantity here is an array.
It's a 1 by 100 array, and it's being multiplied by itself, right? We're squaring it. Math in MATLAB is matrix algebra.
Thus, it's trying to do a 1 by 100 times a 1 by 100 matrix multiplication, and that's why we're getting this error. Think, how do we do element-wise operations? We just want each of these x's, the first value of x, to be squared, the second value of x to be squared, technically first value minus 3 to be squared, second value minus 3 to be squared.
That's an element-wise operation. Add a dot. It even tells you right here to perform element-wise matrix powers use dot and then the caret. That's exactly what we want. Let's add the dot in there.
Good. And then finally we need to add 10 at the end. To ensure that order of operations are happening, and by all means MATLAB is extremely smart and will do these appropriately, it's more so for us as the programmers, I like to add in extra parentheses. Do not, do not, do not add any other type of brackets or braces.
No, no, no, no, no. Brackets are used when you define matrices, right? A equals 0 and 1. That's only, only, only, only for matrices and arrays, alright?
Parentheses are dedicated for orders of operations and for indexing. So use multiple, multiple. You can do double things here, whatever you want.
Do not use brackets. Do not use braces. Don't use these things. No, no, no, no, no.
Those are for other things in MATLAB. Just the parentheses here. And then I'm adding 10 afterwards.
Great. So I've got x on the range 0 to 5, y, taking those x values, subtracting 3 from each of them, squaring that quantity, taking the opposite of it, and then adding 10 to it. Fantastic. But I'm a visual person. I love to see things and that's how I learn and understand.
If you are too, then this just isn't doing it for you. Yes, you have all these values and we can find the maximum one, but let's first plot this. We're going to use MATLAB's plot command and just give it the x value and the y values that you want to plot against each other.
Hit enter and we've made our first graph in MATLAB and it's beautiful. X-axis are our x values from 0 to 5. Y-axis we see goes from about 1 to 10. And we have to find our max y value. Looks like it's going to be around 3 right now, but this just gives us a good idea of what we're working with. We're going to cover plotting more advanced later in this, but for now, basic plot. What's actually going on though is that this isn't a contiguous line.
These are just all the 100 data points that we've plotted. Really quickly, Just change this and add this argument. You're adding a character star.
Put that in there, and you'll see on this graph all these little stars are the data points that we calculated. That's what I'm talking about. We've got a computer here that can do mad computation.
Let it do its thing. Also, now that we've got plots being made, I've added this close all command. That will close all those figures that we have up. every time we run a new script, and when we plot it'll be on a brand new figure, so we get the new plot showing every single time.
But we still have to answer the question, what is the maximum y value? And this is where MATLAB's built-in functions come into play. MATLAB literally has a function called max. If we give y as the argument, we'll get the maximum y value out right here.
You can see it's just about 10. The reason why it's not 10 is because we're not checking every single infinite value that exists between 0 and 5. We're only checking a hundred of them because that's what linspace gives us. Is this answer correct? Just about.
It's pretty darn close to 10. But note that this is a numerical solution, whereas 10 would be the actual theoretical solution. If you want to find the minimum value, how would you do that? Well...
You've likely figured out that minimum y is probably the one that'll do it for you. And this one comes out to an even one. But let's say you didn't know the name of a function, right?
I clearly know max and min. Those are easy. But if you're looking for more advanced functions, how would you even begin to find this?
MATLAB provides awesome ways to get help. First and foremost is my favorite. You click this little fx down here, and this opens up a search for functions. Boom, I've already got minimum searched in here, and you can see all the functions that in the description have minimum in it.
If you want to take an integral of something, you're going to search integral in here, and boom, numerical integration. All these different things that are built into MATLAB that you have at your disposal. Maximum again. Here we are. Let's say you want to round values.
Ceiling, floor, fix. You've got all these options. Take advantage of this tool simply by clicking the little f of x in the bottom of your screen.
However, I've now found these functions. How do I know what their arguments are? MATLAB has this covered by doing help and then the function name. If you run this in your command window and then open it up a bit more, you get documentation on this function. Min.
Minimum elements of an array. It's the smallest element in the vector x. What's x?
Right here. It's your argument. And it tells you all these conditions for what this function does. You can also type doc and then the function name and it will open up MATLAB's online documentation for this function. It's basically the nicer version of what we saw in just plain text there before.
You've also got this help bar that you can search in. I can look for the maximum, search this and I'll see that there's a cumulative maximum function, some sort of name length max and moving max. This is the max that we're going to be using here. just the maximum elements of an array, there is so much help.
And guys, if you aren't peeing your pants right now and subscribing to this YouTube channel, oh, you've lost your mind. This is gold. As a programmer, you are never, ever, ever, ever expected to know all the functions and all the possibilities of a programming language. No, no, no, no, no. You need to know the basics, and then you need to know how to find information that you need.
Almost every time that I program in MATLAB, I end up going online, going to this documentation, and searching for something new. The other way to do it, you open up a new browser on the web, and you say, how to find the minimum of an array in MATLAB. Look this up. Boom. MathWorks website has a hint.
Boom. Right here. All this help is available.
Guys, you are not alone. Did you see when I was searching for this right here? Look, in Java. Python, C++, JavaScript, they're in MATLAB already.
In C, everyone, everyone has to get help in these languages. The internet is the best resource for you. Guys, the world is your oyster here. Take advantage of it.
Anyway, I digress. Let's get back to our problem. All right, we found the max and the minimum using the max and min functions.
At what x value does the maximum y value occur? Okay, well the maximum y value I think we found was about 10, so we need to go back and find that x value. In our script, let's take a step back.
We've got max of y, that's good, but we need the index of that, right? At some x value, we put it through this function here, and we got some y value that was the maximum. So if we work backwards, we might be able to get that index.
And this is where reading about the functions help. Help max. Let's take a look here. This third paragraph.
M I, max of x, also returns the indices into operating dimension corresponding to the maximum values. Ooh, that's exactly what we need. The index is what we want. Let's try a couple things here. Let's try, first let's just save this to max val and do max y.
I'm going to suppress some output here. We don't need a plot right now, so I'm going to comment this line out. So MATLAB won't even run this. And now if I run, boom, we're just getting that maximum value out.
As we saw before though, in that help thing, it said if we do m and i, we're going to get the maximum value and the index of it. If we run this, we get two outputs now. This is how you take multiple outputs of a function. You actually pass it in a matrix of values, and then the function will assign appropriate values to these outputs.
Now I've got i equals 60. That means the 60th value of i, if we open up, sorry, of y, if we open up y, 1, 2, 3, 4, 5, 6, you know, if we go all the way over to 60, 60 should be, boom, right there, the value we were expecting. That means the 60th value in x, is the one x value that gives us the maximum y value. 60, right here.
So 2.9798. Of course, guys, you don't have to go and open this up every time. We're smarter than that. We can just do x of 60, and that'll give us the x value. Better yet, let's come here and let's do x max val equals x of i.
What is this i? It comes out of here and it has the value of 60. If we run this we'll get x maximum value 2.9798 and this really gives us the maximum value of the y function. The last question they asked us was how to find the y value of any given x.
This is not something we can do by just generating all these different points right that'd be exhaustive. I could give you any x value, right? 9.99999957892, right? And there's no way that I was going to calculate that in my linspace. So at this point, we need a different approach.
What we're going to do is define something called a custom function. More specifically, MATLAB calls these anonymous functions, but they're just what we're used to when we plug in a simple value into an equation and we get one output. And we're going to say at x. y at x equals this. If we run this, we get an error.
Guys, I can honestly never remember how to define anonymous functions. You know why? Because I can open up a new browser and type anonymous functions in MATLAB.
Heck, I've even made a YouTube video on this, but I don't remember these things because they're very quick and easy to look up. Here we are. We do at, ah okay, I just forgot to add parentheses around x.
Not a big deal. I come here, parentheses around x, and we're good. I run this, no more error.
But y is defined differently. If I output y right here, it's no longer just this entire thing put through our function. It's actually a function handle. What the heck is this? Don't worry so much.
Know that you can now use y and plug in any x value that you want. Run that script, and there's your answer. It's a massive number. Also note that MATLAB uses scientific notation here. This is times 10 to the sixth power.
But now I think we were asked the y value of 20.2, something like that. We can run this and there we go. If we input this value of x, we get this value of y out. These are called anonymous functions and they're very quick and easy methods to get outputs.
The problem actually called for us to do y of. 20.7, so I'll go ahead and do that for you. We run that. Note, it can be a little bit confusing because previously we've done something like this, where x of two is actually the second value in x.
Note that these are very different. X here is a matrix. It's a one by 100 array of values.
Y isn't a matrix or array. There is no index to y. Y is defined. as a function handle. These function handles, they don't have multiple components like x does.
x has all these values we can choose from, y does not. When we give a value to y and it's a function handle, it simply inputs that value and then runs it through the equation. And that's why these look similar but act very different.
Here is another question to consider. Plot the equation from x equals negative 10 to 10. of, it's that same formula we saw previously. Part B is gonna be, we have to change the curve to add 15 instead of 10, and then part C is change that curve again, but we're gonna do x minus five quantity squared in the parentheses.
This is prompting us to think more about plotting, we're going to cover that for the next few minutes. Let's start fresh in MATLAB. Here we've got x and I've changed this to negative 10 to 10. We aren't going to be using this anonymous function form anymore.
I'm just going to clean this up to what we need as the bare minimum. And let's run this to make sure things are working. I've called our y y1 because for part b and c we can create a y2 and a y3. I'm just going to copy this for now. It's going to be the easiest way to make this work.
There's our y2 and our y3. will be like such. Very good.
And our y2, we add 15. And our y3, we do this as a minus 5. Excellent. This will get us our three curves. And if we run this, good. We've got 100 values for each of these y's.
And then we can plot all those values because it's against the same x, right? We're using the same x value, negative 10 to 10. for all these different Ys, and these will give us our three curves. Essentially right now, we have three different pairs of data.
But before we get into plotting these, and I want to plot them all side by side around the same graph potentially, let's just start talking about plots and figures in MATLAB. MATLAB calls these things a figure. In our command window, let's just do figure1 and hit enter. It's going to open up this window, and it contains a blank figure. Not very eventful.
But as we begin to plot things on it, for example, let me do a split screen here. It'll be easier to see. Here we go.
Here's our figure that's just all blank. Let's do plot. Alright, we do this, and there we go. The plot is starting to be populated.
Now if I did plot x and then y2, we'll see there's a slight, a very slight change there actually, not substantial, but let me plot the third one now, y3, and there's a, that was a much bigger change. The curve shape is staying the same, but if you look at our axes, those are shifting. What Matlab is doing, it's rewriting this graph on the same figure. See we still have figure one right here. The proper way to do this, to add multiple curves of the same plot, is going to be using the hold on command.
Okay, so here I've got y3 plotted. This is the most recent one that I ran. If I did hold on and then plotted x versus y1, aha, there's our other line.
Let's do that again. Hold on and plot x and y2. There's our third line in yellow there. MATLAB's automatically recognizing that these are going to be different lines, and hence it changes the colors being used.
But let's make it ahead of ourselves. This graph is actually pretty crappy. We don't have any axes labels. There's no title. This is kind of garbage for now.
Let's start a new plot here. Let's call figure two, and you know what? Let's do all this second figure work back in our script. I'm gonna go full screen here again.
This close all is going to wipe out all those figures and we're starting fresh. Let's start with our plot. So plot of x versus y1. We run this, we get what we expect.
Let's add an x label. That's gonna be our x axis. This is simply x. Great. Same thing for the y axis.
Let's do y label and y. Could not be simpler. You can, I like to do these with a comma, but you can put them on separate lines.
It doesn't matter. You run these. and it's created.
We can be more specific here and specify what figure we want because we can create multiple figures and plot y2 on that second figure. Now two figures will pop up. Here's our first figure which has the x and y on it and the first curve and here's the second figure which has our second curve.
Notice that these x label commands, when they follow a plot, they go on that plot. Here The x label and y label commands come after this first figure plot. And then right here, we plot the second figure, but we don't have any x axes, y axes labels.
Once you command a plot, anything that follows will go on that plot until you start another plot. Let's keep rolling with this one. Let's add a title using the title command. We call this y versus x.
And we kind of had this as like problem A from our problem set. So it'd be nice to have that graphed on there too. So it specifies there's our problem A. I like having grid lines on here.
It makes things a lot clearer. You're just going to call grid on, run this, and we're pretty much there, guys. This is looking like a very nice graph. The only thing, and this is getting nitty gritty at this point, we should be plotting data points because these are just simply raw data points right now.
Right, this isn't a curve. This isn't one continuous curve. Y1 and X1 are 100 data points.
So we really should be plotting these as those stars as I talked about earlier. And that way, it's a bit more clear. I'll go full screen here to see that we're just calculating Y values at different X values along the way.
It creates the shape of a curve, but it isn't overly misleading of what's going on here. If you want to change the color of these, the shapes of these, how do you think you'd do that? What have we talked about so far when you need to get extra help on a command? Throw this in your command window, help plot, scroll up a little bit, and you'll see there's a whole plethora of gold guys.
Gold right here. Blue, green, red. These are all your blue, green, red. These are all your colors.
You can do different shapes and things, and then for your lines, you can create different things here. Let's go ahead and do that. You add all those things right in here.
So if I wanted to do blue stars, I'd do blue and then star. What about blue circles? B-O.
How about magenta squares? Let's do M-S. I'm not going to plot this figure for now. Just the one.
And there we have magenta squares. Kind of fun, but very useful to make sure you're separating out the different things that you're plotting on the same graph. And that's what we want to do.
I want to plot all of these curves on the same graph. To do that, we already discussed the hold on command. Let's do plot.
X versus Y two, and let's make it something different. Let's say we want these to be, I don't know, blue triangles, I think that's gonna be triangles. We can do that, and then those will be added on. Note that we didn't have to add any more X label and Y label and title stuff, because we already added that to the figure, and now we're just adding another line here, another data set onto the figure.
Very cool how this works, but you can see every diamond here. is simply a little bit higher than every square. You can click these points to get the actual values that you're calculating, by the way, and you'll see that we're just slightly above as you go along the curve here. Last thing we have to plot is going to be that final curve.
Let's do y3 and let's plot that as, I don't know, green. Let's do plus signs for now. We'll go ahead and do that.
And now we have our green plus signs on there too. But if you just showed someone this graph, they have no idea what equations you're using. They don't know what these belong to or how they relate. What you need to do is add a legend.
Go ahead and do the legend command. See, this is so straightforward. I love plotting in MATLAB.
I hope you're seeing how easy this is and straightforward. You just keep adding the things that you want and MATLAB will keep adding those to your figure. We'll do legend and then we need to name the legend entries. I'll do Y1.
Y2, and Y3. Note these have to be given as characters or strings, and then MATLAB will add these to our graph. And it goes in order.
Okay, so the first thing you plot will correlate to the first thing that you name. We do this, and MATLAB will add an automatic legend in the top right. You can click and drag this, by the way, and move it around so you can make it easier for your viewers.
You've also got a lot of tools built into this chart. Look on the right here. You click this hand.
That's your panning hand. And then if you go and click on the graph, click and hold, I can scooch this and now change the viewing area. Let's see how much axes are changing right now.
Pretty cool. After that, I can click the home button to go back to the actual view. You can zoom in, click the plus magnifier, and I want to zoom in to where all these peaks are happening. Click and drag.
And now we've zoomed in to all these peaks, pretty cool. I can also zoom out by just clicking the zoom out and clicking around the screen here. And you can always go back to the home at the end. If you want to copy this figure and put it in another document, you'll click the copy figure button right here, and that'll enable you to open up a PowerPoint presentation, a Word document, or something like that.
You'll copy the figure. You can also save this figure and do a couple other things here. But mainly edit, copy figure, and paste it into something else.
If you want to change the axes ranges, for example, yeah we did x from negative 10 to 10, but maybe I just want to hone in on a specific part, you're going to do xlim and then pass a matrix here. Okay, this matrix is going to be what you want for your lower limit. I'll say 0 to 2. So this matrix is your actual limits, okay?
You run this, and then you'll see our x-axis is now just from 0 to 2. If I wanted to change the y-axis, you guessed it, y-lim, and I can do this from 0 to 100. Run this, and now you'll see that the y-axis has changed, only looking from 0 to 100. Remember, I can still use my pan tool to look around here and see the other curves. I can use my magnifying glass to zoom out a little bit more, see some more of that curve, look around. These tools are here for your disposal.
Last thing, if you want these to be filled in, you have a couple attributes that you can change. So these symbols, let's say I want to fill this in. You're going to do an attribute name and then the value of that attribute. So here we want to do marker face color and then I want that to be magenta.
And let's say I also want to change the marker size and I want that to be size 10. You're probably thinking, where is he getting these things? Where are these attributes stored? Where can I learn more about these attributes?
Use MATLAB's help. Scroll around, read these things, google them. You can always find more information on this stuff online and using the stuff that I've shown you in the command window.
I think it's got them here somewhere. I'm just gonna look for marker size and see if they use this at all on the page. Here we go. We've got marker size 10. We've got marker edge color.
Ooh, okay, so here they changed the edges to kind of a blue. And then they did marker face color, changed the face values. You can change the lined width, so those lines that I was plotting earlier, you can change those.
Let's go back down here. Let's plot what we have. Here you can now see our axes are still kind of off here, but there we've got those squares that are now filled in. A little bit easier to see. These green things are kind of difficult right now, but you get the notion.
You can play around with these things. You call an attribute, and then you call the value you want that attribute to be. And then with your lines, if you wanted to plot this as a line, you can add a dash dash in front. We do this and you'll see we get a dashed line with the squares on it. If you want to get rid of the squares, well then you don't specify the shape that you want to plot.
I'm going to get rid of our our limits here because these are kind of annoying. But if you don't specify the shape, then you'll see we just have a dash dash line that's magenta representing our y1 curve. You'll notice that we've put all of these three curves on one single plot and we did that with the hold on command. MATLAB also offers us the option to split these into three different plots or put them on side-by-side plots. I'll show you what I mean.
We can create those different figures. Remember when we did the figure one and the figure two? Let's put these all on separate figures. So instead of hold on, let's just do a new figure and a new figure and we don't need a legend anymore because we're putting these all on different figures. In fact, three figures.
Let's run this and you'll see that we now have three figures each for a curve. That's one way to split things up. And then you'd have to add for every figure these.
You have to do the x label, you have to do the y label, you have to do the title. You need to add all that stuff to populate these graphs as well. Another option you can do, and depending on your application this could be very useful, is using something called subplots. You can do help subplot and you can learn more about the subplot approach. But what subplots do is basically you're creating this like a matrix of graphs.
You know how we have a 2x2 matrix and we have values in all those 2x2 spots? We can do that with plots. We can call subplot. I can call 2x2 here and then specify the place I want my first plot.
Let's just call it 1 for now. But this will create two rows by two columns of plots. Get rid of my other figure commands for now. Let's just comment these out so we don't get confused. And I'll show you what this looks like.
There, okay. See how this plot is in the top left of a two by two? Looks like a matrix of graphs almost, right? This is the layout. So you can put these plots, it's in the same figure, but it's in a different area of the actual plotting area.
It's kind of hard to describe this with words, but I think you guys are seeing it from the visual. Let's say I want to add all the other curves then in these other spots. I would do subplot, same subplot here, so you keep the same dimensions. Then I'm going to add two because I want this one in the second position. Let's go plot and do this one.
We'll see this one come up now in the second position. And it goes top left is one, then two, then three, then four. Let's get this third plot on there as well. 2, 2. Let's put this... Sorry, this one should be in the second spot.
This one should be in the third spot. Uncomment it, and we'll end up with this beautiful graph. Again, we need to add all the labels and the titles for every one of them if we want that. Let's go ahead and just copy those in right below those plotting commands.
Those will all be populated. But this, a 2x2, isn't the appropriate approach. for these graphs, right?
What would be better? What would be a more visually appealing method for this? What type of matrix?
A 1x5? A 10x10? Hopefully you're thinking maybe a 1x3 or a 3x1?
We've got three graphs here. Let's go ahead and do that. Let's do 1x3 for all of these, and this will give us one row of three charts. Then as we expand this out, we get a nice side-by-side visualization of these three plots.
And that'll be a sufficient answer to that problem we started with. about how these curves change with different parameters. Let's take a stab at another question.
Here we see, based upon the following equation, what percent of y values are greater than 0.8 for x equals zero to 10? We have y is the sine of x. This is one that, if I'm being honest, I don't even know how I'd solve this analytically.
You know, with, what would we set our equation? Would we solve for values at x equals 0 and x equals 10 and try to plug these in and then look at the the period of the sine wave? This would be a tough one to do with paper.
I honestly don't know how to do it. I'm sure there's proofs and things like that, but if we break this down, we know that the sine of any any input there will be from negative 1 to 1, so we know that some values should be greater than 0.8, right? We'll have something between 0.8 and 1 for I don't know how many x values, but that'll happen. So that's at least good. So it's not zero, but we'll need to essentially check some data points.
Similar to when we plotted, we developed x from 0 to 10, we calculated some y values, and then we had those individual points that we plotted. Remember that? We're essentially going to do that, but now we need to check if those values are greater than 0.8, and then we'll have to sum those up and see how many we have and divide that by the total amount.
That's going to be the approach for this problem. We have a clean slate in MATLAB, and I've got our x going from 0 to 10, and our y is just the sine of x, nothing too eventful here. I like to plot things.
Again, I'm very visual. I'm going to go ahead and make a plot of this just so we see. We've got an idea.
Okay, let's plot this as points again. We don't want to confuse ourselves what's going on. Just do dot, and that'll give us just points. And if we look closely, here's point eight.
And it looks like it's gonna be some portion, I guess this is around 15%. You can hold me to it, we'll see how this problem goes, I have not solved it yet. But we can, I mean, if we were really desperate, we could just count these points and divide by the total number of points.
But I'm trying to teach you guys basics of logic in this problem. We have our points, and we're getting real fancy. What we can do, let's do hold on, plot another thing. Let's plot just the x values.
Let's do one at 0 and 10. And then let's do y at 0.8 and 0.8. See what I'm doing here? I'm not creating actual x and y things to plug in here. I'm just giving them the direct arrays.
So that'll plot 0.0, 0.8, and then 10, 0.8. That'll give us a line. Let's make that a red line that's dashed.
Alright, let's do that really quick. And now we can get a better visual for, we're looking for all these dots above this red line. Kind of cool. And we're going to add some more line, sorry, we're going to add some more points here.
Let's make this, geez, 100,000 points. Matlab will have no problem for this, by the way. It still takes like no time to run, but we have a lot more points now.
You can't even see that it's not a line. These are individual points. That'll give us a more accurate answer than if we did, I don't know, just 10 points.
Right, this is a very inaccurate approach. You can hardly even tell this is a sine wave. So it's always better to run more points, especially when we have the computation ability with modern computers.
Sounds good. We need to check if these values are greater than 0.8. This is the basis of logic. Logic gives true and false values out after you present a logic statement. Let's start by just saying x equals 5. No problem there.
We're just back to our command window. And let's do x is greater than 2. Run this and we get the logical of 1. This is telling us, yes, your statement here was true. Remember, computers started with zeros and ones, and they still are zeros and ones, by the way. We've just progressed to languages like MATLAB where you don't have to type 00101100. But the bases of these things are still zeros and ones. Let's do x is less than 2, which should be the answer here.
If 1 is true, 0 will be false. And you can even, I can even type true here and get the logical out of 1, and I can type false and get the logical out of 0. Thus, if we want to check multiple values, let's define a as just a matrix of ones. Let's do a 1 by 10 matrix of 1, so A will just be a bunch of 1s here.
What if we did a is greater than 0? What will come out? MATLAB will perform this logic assessment on every element of a. 1 is greater than 0, 1 is greater than 0, 1 is greater than 0, and thus we're just going to get the matrix out of all trues.
Maybe not the best example. Let me do a is 1s and then multiply this by 5. So we'll have a bunch of 5s, and now we can do our logical test. a greater than zero and we get a logical array of ones out, which is telling us true true true true true true true right?
This is exactly how we get this information in zeros and ones and now we can use Zeros and ones to easily count I can use the sum function having been discussed You probably knew it existed sum of a will give us 50 This is just summing up these 10 values, but if I save results to the logic statement a greater than zero. My result is this true, true, true, true, true, true, true array. And if I sum result, I get 10. This confirms that 10 of the values in a are greater than zero. There's tons more logic to do guys. I'm going to run through really quick some of these other logical operators.
You could do eight greater than or equal to eight true. You can do this. 19 plus 5 is less than 100. True.
You can do 55 does not equal to, this is a fancy one here, a tilde, 20. And that gives you logical of 1 because 55 does not equal 20. By the way, on your keyboard, this should be like the very top left. Shift and hit that one. The dash is what's next to it, this little thing jig. I call it a tilde.
Maybe it's an e tilde. I don't know. Other stuff, you can do compound checks.
So maybe 10 is greater than 5 and 11 is greater than negative 100. So this will check is 10 greater than 5. That's true. This will check is 11 greater than negative 100. That's true. And if both of these are true. Then it'll output true.
Okay, this is kind of getting to the whole field of logic. You may or might not be familiar, but these ands require both of these correct. If I did an or, actually, let me make one of these false.
This is false, right? 11 is not less than 100, so we get false. Because both of these are not true, we get false.
That's the power of the and. If we look at or, let me take this. and do OR, which is just a vertical bar, OR 10 is greater than 5, that's true. 11 less than negative 100, that's false. But only one of these has to be true.
Only 10 greater than 5 OR 11 less than negative 100. If I run that, I'll get true. Okay, that's all I want to cover on the logicals, but let's go back to our problem. We have to figure out what percentage of our values in Y are greater than 1.8. How do we do that?
Well, if a value of 1 is greater than 0.8, that'll give us a 1 out. So maybe we can compare this entire matrix of y's. y greater than 0.8.
Let's see what our output is. Oh my goodness, yeah, we have a lot of values here. We're going to get a ton of stuff, a bunch of zeros here. Let's keep scrolling through and see if we find any ones.
There are so many values. Ah, here we are. Found a bunch of ones. That's good.
That means our test worked to some degree. Let's sum up those values. Let's save this as y. I'm going to do y underscore greater.
That's going to hold the array output of this. So now this will be saved to y greater. I'm going to stop plotting this for now. And y greater is the same size as our y value.
But you can see in our workspace it's got a check next to it. Because if we do whose, take a look, our y greater is a logical array. It's not the typical double that we see before. But we can treat this as something that we can sum up.
Let's do the sum of y greater. And that will give us the total number of values that are greater than 0.8. Then we can divide this. by the total number of values that we generated. And that'll give us...
the percent of values that are greater than 0.8. So let me do final percent as a variable here, some y, we have those values, and then I'm just going to divide that by, yeah if we could cheat here we could change this to be, you know, we could just copy and paste it there. That's bad form, because what if we change this to 100 values? Now we have to change this to 100 values.
Instead let's do the length of y. New function here. Length of y will give us the length of y.
How many elements are in y? You can also call height of y, which would give us the number of rows, and you can call width of y, and that'll give us the number of columns. Length will always give you the larger of height and width.
Great. We call length of y, we run this, and we get final percent is 0.25. Kind of cool. And now, let's actually ramp this back up, make sure we have more.
And you can see that our number changes just slightly here. It increases to be more accurate. If we just do one value, yeah, we're going to get zero because the one value we sample didn't actually do anything.
If we do 10 samples, we say it's about, you know, 20% of the values. And if we increase this. to a thousand, we start honing in and the value doesn't get any more accurate. So we're just dealing with 0.2574 as the answer to our question.
If you want to technically make this a percent, you can multiply this by 100 and then change this to be 25.74%. This was a super quick intro to logic statements, but very often these things are super useful for quick checks of things like we did in this problem. One cool thing we can do is change this 0.8 value, and we can now check if things are greater than 0.5, let's say.
But we're also going to want our plot to update. Let's create a new variable and call it yCheck. That's the value we're checking against.
And I'll call it 0.5 for now. And we can replace this with yCheck and yCheck, and then this with yCheck. This is good programmer form. You want all your parameters to start at the top, then come in and do your actual actions, and then have your final output.
I'm being sloppy here, but work with me. You get the idea. We start out and we define parameters.
These are the things that we change very easily and quickly, and it commands the rest of the code. Imagine you've got hundreds of lines here. You don't want to go back searching for wherever this value made sense or whatever. You know, you want these things to be consistent so you can update one value, like ycheck, to zero, and then automatically your code follows suit and updates in those places. Now if we run this code, look, our line adjusts to zero and the final percent is updated as well.
If you're wondering why half the values... If it's a sine curve, half should be greater than and then half should be less than. It's because we're going over one and a half periods of a sine curve here.
If we adjusted this to be right here as where we cut things off, looks like it's about, let's see, what is this point here? Let's actually change this to prove what I'm saying here. Looks like it's around, I don't know, 6.3.
So let's change this to 6.3. What else do we have to change? This value right here to 6.3.
So let's now create a variable called maxx and do maxx and then this equals 6.3, 0 to maxx. We run this and there we go. We have got about, it's about one period then, one crest, one trough, and our final percent is just about 50% there. I was eyeballing it, but that makes sense.
It's a good logic check to know that our code is running as we expect it to. That's the final lesson to take away from this as well. Don't just blindly send stuff out into the ether and hope that MATLAB is doing it correctly. MATLAB is doing what you tell it to do.
Your parents at some point probably told you that computers are stupid, and they are, because they listen to everything you do. And if you're stupid, then you're gonna create a stupid output. I'm not calling you stupid. But garbage in is garbage out.
You can write a crappy program, and it's not going to give you a good answer. You need to write good programs that you are confident in and those will give you confident, accurate answers. Let's take a stab at this problem.
Part A is to generate 10 random numbers from 1 to 5. So randomly generate a 3, randomly generate a 2, a 4, 1, 5. This will be from a uniform discrete distribution. And then we want to count how many 3s there are. In part B, we're going to display the word wow if there is more than 20% of the numbers being 3. In part c we're going to do a and b again but using a for loop.
We'll introduce the for loop mentality here and then we're going to extend this instead of 10 random numbers to 10 million random numbers and we're going to compare the speeds and the time it takes to compute using the two different methods. We are back to a blank script in MATLAB. I'm now using Ubuntu as my operating system. For those using Linux distributions out there, Windows was the first half of this class.
Nothing changes, by the way. It's basically the same exact approach, the same syntax that MATLAB is using. You'll only notice some differences in the IDE, but for learning purposes, it's the exact same, just offering potential comfort to those of different operating systems. First thing here, as always, We're going to clear everything in the command window and clear our variables.
We need to generate our random numbers and I'm going to call this matrix A. A will hold our random numbers. If you want to find some other random commands feel free to look around the webs.
I'm going to use randy. We can find more about randy by taping help randy. randy is going to generate integers with a uniform discrete distribution.
That's exactly what we need. Let's go ahead and give the arguments five. So if I just run this, a is four. If I keep running this script over and over, we're gonna see that that random number changes. So this is generating just one random number from one to five.
I want 10 of them. I want a one by 10 matrix. And here we're getting random numbers, 10 of them from one to five.
Great. The first thing we need to do, was to count how many threes there were. If you recall, we've done some logic checks. If something's greater than three, if something's less than three, if something does not equal three, well, let's try just running something like this.
The fifth term equals three. So we can check a single term if it equals three or not, and you'll see in the output there, we just got a hit. Logical is one as our answer, and the first, second, third, fourth. The fifth term is 3. We were basically just checking this single term here. Remember as we learned we can do this for whole arrays so we can just check in general if a is equal to 3 and we'll get an entire logical array out.
In this case we didn't get any 3's so our logic array is just a bunch of zeros but as we do this in this run we had looks like four 3's. To count this all we do is add a summation around our logic statement there, which will sum these up and give us the number of threes. So here we have 2 2 1 2 0 2. Occasionally we should get 3, all right? Here's 3, and we wanted to display wow if this happened. This is where we can introduce the if statement.
The if statement will act if a condition is true. For example, if This value here, which we discovered was just outputting 3, it outputs the number of 3s that we have in this A matrix. If that is greater than or equal to 3, then we will output using the display command, wow.
And then we have to end the if statement. You'll notice that every time we open an if, you have to do an end to the if. This display will simply output to the command window and we can begin to run this.
There we go. There's our first time. We have one, two, three, four threes in this one and that time we were able to display wow to the command window. When this statement right here that I have highlighted evaluates to true then we get an output to the command window. because we asked for it right here.
And to be thorough per the problem, it wants us to output the number of 3s. So let's go ahead and do this as num3s equals the sum of a equals 3. And then we can just replace right here num3. Then with our output, we'll get the random matrix a, the number of 3s that we had in the matrix, and when num3 is greater than or equal to 3, will display wow. Run this a few more times so we get one more hit here.
There we are, wow we had three, sorry we had five threes in this run and we displayed wow. That's the basics of the if statement. From here our instructions were to go ahead and do a for loop with the same mentality. I'm going to introduce you to a section notation. To percent signs side by side Introduce a new section you can see this blue highlighting here.
It might be white it might be black depending on your system setup We're creating a new section right now, and we can run each of these sections Differently this will be section one up top and this will be section two down below we can be more specific on what we're calling them. This is the if statement approach, and down below in section two we have the for loop approach. It's these double percent signs that define a new section. The benefit of this is that in each section we can kind of run them independently, and they act independently of these other scripts that it's involved with in the same.m file.
So if I run this script down here and just say x equals 10, and run this, Everything up here is still the same nothing changed I only ran this section got my output of X equals 10 and a new variable was created if I do CLC and clear vars down here and run this it's as if I'm just running this own section here Which is what I'm doing MATLAB only runs each section Independently control enter is the best way to run your independent sections You can also come up here to your run button. You've also got run section on the left, and that'll be your section depending on where you're running. If you use the run button in general, it'll go through and it will run the entire script. As you can see, we end up with just x equals 10 at the end because of this CLC and clear var statement.
Run will always run the entire script. Run section. just runs the individual section that your cursor was in.
That's because that's the active section and MATLAB assumes you want to run that individual section. Let's start with a clean slate to discuss for loops. For loops are more advanced programming techniques and can be very challenging for beginners so please don't be put off. I promise you you'll get it. They're useful when you need to do the same thing over and over again.
You do a for loop for a specified number of iterations and then it stops and the rest of the code will continue to run. Of course, it's best demonstrated with an example. Let me go ahead and write a for loop.
For i equals 1 through 10, let's just output i and then end the loop. I'm going to run this and we're going to see in our output that i is just being outputted. 1 to 10. So what's going on here? Well, you know 1 to 10, right?
You've seen this before. If we just do that in our command window, it's going to do what? Just give us 10 values, 1 to 10. No surprise here.
But we're using this variable i, and this could be any variable. It doesn't have to be i. i is just what's typically used. You could call it a counter if you want to, and then change this to counter, and counter is going to go from... 1 to 10, you could call it your friend, in case you don't have any friends.
Oh look, at the end you have friends that are, you have 10 friends. See, look at that. Programming's beautiful. The fact is, we're going to call this i, and it's a placeholder value that you're using in each of your loops.
But what's actually looping? What is this loop iteration that we talk about? Every time this runs, the value of i...
will change. i starts at 1, i equal to 1. And then this code is executed. And if I have multiple lines, like i plus 1 and display i and all these things in here, all this stuff between the 4 and the end is run with i equal to 1. So if I run this and scroll up during that first iteration, oh, let me just clear some stuff here.
Sorry about that. CLC and clear vars. So we just have a clean output here.
We get i equals 1, and then I added i plus 1, and then I just simply displayed the letter i, which happened right there. See how I displayed the letter i and not the actual value, which would be i, like that? Just the letter i.
Every loop... Every time we run this code, the value of i will change. It starts out as i equals 1 because we asked it to right here. In the next loop, once it hits end, it goes back up, it goes back up, and i becomes 2 right here.
i equals 2 because of this statement here. Then we add i plus 1, and we get the answer out to be 3. And then we display the letter i right here, i. That's all the commands, so we go back up. i now becomes 3. i equals 3. 3 plus 1 is 4. Display the letter i. And we do this over and over and over until we get to 10, which is why the last loop is i equals 10. i plus 1 is 11. And display the letter i.
We get to set the number of loops, right? We're telling MATLAB we only want i to go from 1 to 10. If I want i to go from 1 to 10, skipping every other number there, remember just like we did earlier, this will go 1, 3, 5, 7, 9. If I run the code, i is 1, then i is 3, i is 5, i is 7, i is 9, and we have all the other outputs that we asked for as well. This is for loops.
While loops are different and we'll cover them later. How does this relate to what we're trying to do though in our problem? We're trying to count the number of 3's. How is this even useful? 4 loops are very useful for going through numbers in a matrix.
We can use this i as an index. So we could go through and if we called i, or sorry a, like we had up here, we could call a, we could call a, and we can go through and then do checks on each of the individual components. Let's generate this random A matrix down here now, and instead of going from 1 by, you know, 1 to 10 here, let's just go from 1 to the length of A, and the length of A will be what?
It will just be 10, because it's a 1 by 10 matrix, and 10 is the longest dimension. We'll go through from 1 to 10. And I'm going to check all these values inside. a, i. We'll start with this.
Let's run this. What'll happen? i is 1 to start.
We run this, and this is equivalent to running a, parenthesis, 1, which gives us the first term of a. On the next loop, i becomes 2. This becomes a, 2, which gives us the second term of a. So it'll end up printing out line by line here what a is. Here a 2 1 4 4 2 1 4 4. It's just going through each of those indices. We want to do a logic check, right?
We want to see if that value is going to be greater than or equal to 3. Count the number of 3s. So we can do a is equal to 3 here. And we'll get logicals out, right?
We're getting all these logicals now. 0, 0, 0, 0s, all the way down. We get, oh, geez, three 3s in a row at the end. There they are.
Now we need to count these. Ideally, we'd establish some sort of num3 variable again. That will equal the previous value, and we'll just add 1 to it. So every loop that we get this to be true, ah, we should make this an if statement.
So we should do if ai is equal to three, then we run this and we'll end that if statement. This is called a nested if statement because it's inside of another loop, nested if. So if this term of a is equal to three, if that evaluates to true, Then we do this.
We say num3 is equal to the previous value of num3, and we add 1 to it. We're counting these values of 3 as we go through the matrix. If we try to run this, we have no 3s in that one.
But here, we have a 3, and we're going to get an error. And that's because we didn't define num3 before this loop started. So MATLAB tried to grab num3. It doesn't exist.
We need to add num3 equals 0 to start because our count of numbers of 3s is 0. We have no 3s yet until we start going through the loop and we count every time that this is added. Let's run it. There we are, num3 equals 1. Run it again. We get two outputs here, right, because the first time we had a hit, we outputted. And the second time we had a hit, we outputted and it added 1. Great.
And then at the end we can add just the same logic statement right here. We can display wow if num3 is greater than or equal to 3. Run this a few times. Let's see if we get, there we are with our wow. If you don't want to have that output every time, you can just simply add a semicolon there. And we'll just get wow.
A bit more complicated than it is for this simple example, but it's often good to learn on examples where you know the answers are true, so that you can check your for loops with it. The final part of this problem was to calculate it with one million variables, as in we're going to generate one million random numbers. And let's run these side by side now. I like to make my sections when I'm initially learning how to do these things, so it keeps it separate. Now that they're both running, let's go ahead and bring this together.
I'm going to get rid of the section notation. I'm going to add a comment down here still so we know this is the for loop area. And just for loop. We only need to generate one matrix of random values. And then let's see what else we need to do.
Num3 here. We don't want to have the same variable that we're using for these different areas. So let's go ahead and name this one num3 underscore. if, because it relates to the if statement stuff we're doing, and then we can just leave these as num3 down here. Actually, we should be good programmers and name it num3 for, right?
And you can see too MATLAB offers to press shift and enter to rename the other two instances. I like that. And now we have num3 for, and we have num3 if in the other section. We can run this all together, and we should get outputs. Only when we have the wows you'll see we get two wows because both sections are displaying them here We can suppress this output as well if we want and we'll just get the random matrix and our wows out The last thing was to compare the times with a million I got distracted there So we want to make this a million so here's a hundred hundred thousand million ten million I believe is what it asked for ten million points.
Let's run this. Oh dear Make sure that you no longer output a. As you can see, your computer is going to try to output a million values now in your command window. Make sure you suppress that.
And notice how greater than or equal to 3 no longer is applicable, right? We're always going to get that with a million, 10 million values. We want to make this 20%, so 0.2 times the number of values generated.
So times the length of A. Same down here. Greater than or equal to 0.2 times the length of A.
Good. So that way, this comparison statement here will change as we change our A value. Sorry, change the length of A. Now if we run this, oh, I have an error. It should be length fully spelled out.
And good. We're able to run this now. Sometimes we output well, sometimes we don't. Makes absolute sense. To time it, to get the duration of time it takes to run a specific section of code, what you need to do is use MATLAB's built-in function tick and tock.
Tick is where you want to start timing something, and tock is where you want to end it. If we run this, MATLAB will automatically give us an output about the elapsed time between tick and tock. To save these as variables, let's call time if.
which is the time it took to run the if section. You do that equal to TOC. We run that and you'll see we get time if here 0.0040.
These are in seconds by the way. Seconds. Let's do the same thing for the for section.
Add tick and at the end add TOC. We want to save that as time underscore four equals TOC. Run this and we have two different times here.
The time to run the if statement What is this, four thousandths? Yeah, tens, hundredths, thousandths..004 seconds here. The time during the four statement section is.0450.
It seems pretty insignificant, right? That's both less than a second. We have all the time in the world right now.
We're in no rush. But this is actually a huge, huge insight into some of the challenges that we see in computing. Four loops in general are going to be slower. And right now, Does it matter in our script?
No, we're not even waiting a second to run this. It's hardly significant. But imagine if you had a script that took four days to run, right? Your if statement version of it took four days and your for loop statement version of it took 45 days, right?
That's a pretty big deal. And even if it's the difference between four minutes and 40 minutes. is a big difference, right? So when you're making your code and your scripts, you want to consider the most optimized method. And this is something that takes years of practice.
I just want to introduce you to it now so you're aware. Tick and Tock are great ways to know what's fast and what's not. The if statement method, this is typically called vectorization because you're just dealing with vectors here. I'm not going through each individual term. I'm doing whole checks on entire vectors, right?
These logic checks I'm performing rather than going through and looking at each individual term of that random matrix. So try to vectorize as much as you can, but again, write stuff that's simple and understandable when you start, and then you can look towards this optimization later on. We ran into a couple things here that I want to point out.
The first are going to be naming conventions. You'll see I'm using some underscores, I'm using some capital letters. There's a couple good ways you want to create variables. There's two main methods.
The first is going to be called camel case and that's where you do this camel case under lowercase first letter and then when you have a compound word you capitalize the second part of it. This could be then let's just say total revenue. equals seven.
You can also do total underscore revenue equals eight or whatever. These are the two main methods underscoring. You just keep everything lowercase and that underscores between compound things. And then total revenue is an example of camel case where you uppercase those other letters for the compound words. You want your variable names to be as descriptive as possible.
A bad variable name, for example, would be four, right? 4 is a word that MATLAB already assigns for doing for loops. So you can't say 4 equals 9. It's going to be thrown off what you're trying to do here. Similarly, you shouldn't name your variables after any functions.
Like the sum should not equal 10. That's bad because what if you're trying to use the sum function? You know, the things that you want to keep clear. So don't use variable names that are the same as function names.
You also can't use numbers to start your variable name. So I can't do 2016 total revenue. If I run that, well, I could try doing, yeah, see, okay.
MATLAB's already telling me, look, you're missing multiplication. It thinks I'm doing this multiplication here, multiplying between something else. If I still insisted, no, I want to save this as a variable, 2016, whatever, whatever year that might be. Right, it's going to give me that error. because it thinks I'm trying to do math.
So you can't start with numbers. You have to start with letters here. The other thing I want to show you is how to do your file names. We can create new files using the new script here. You can also use the plus sign right next to your current and go between.
And you can have multiple scripts open here. This is very useful when you're working on things at the same time. You can use ctrl s to save these really quickly. And make sure you have the.m file extension. The.m extension is needed to save MATLAB files.
Let's say I want to name this file 2016 revenue like before dot m if I click save Matlab is going to yell at me. I cannot start with a number. Matlab file names must start with a letter and contain only letters, numbers, and underscores.
Home stretch guys. The last topic we're going to cover are while loops and custom functions. While loops are in the same family as for loops. They look similar the way we construct them but they have one key difference.
In a for loop, you decide how many times you want to run, right? For i equals 1 to 20, for i equals 5 to 50, you're going to display the variable i and then end. You know how many times this is going to run, right?
It's predictable. You're telling it how many loops to run here. Output is as expected. Just displaying the i as we go through.
In this case, I'm displaying the variable i, not just the letter i. like we did previously. Here we just see a bunch of i's. In a while loop, while, we have to give it some condition here.
And then we do actions, and then we end. Let's do while the condition, and that condition will be something like z is greater than 5, or the sum of values is greater than 9. It'll be one of those conditional statements we've been doing. such as 10 greater than 5. And whenever that condition is true, the while loop will run.
Once that condition is false, the while loop stops. So you can see that we no longer have direct control over how many loops are run, but instead we have control over the conditional statements. Let's do an example z equals 100. While z is greater than 75, we do stuff. We display, let's just say, the square root of z.
I don't know, up to you. And then we have to add a key statement, which I think of as the reduction statement. You have to force, eventually, this statement to become false.
Otherwise, you get in an infinite loop scenario. Okay, if I were to run this right now, and I'll do it for you, I may crash the computer. Let's go ahead and run this. It's just outputting 10s.
You can't tell right now. This thing is just going, going, going, going, going. I have to force quit with control C, okay?
You might even hear my laptop. It's revving up right now. It was just infinitely outputting 10s.
I can show you my, look, I'm scrolling right now. Look at, it's just 10, I mean, infinitely. This would have gone on forever. Force quit with control C if you ever hit this issue.
Why did that happen? Well, z was 100, right? So the square root of 100 was 10, which just kept outputting, and then it went back up to the top, evaluated, is z greater than 75? Well, yeah, it absolutely is. Oh, don't need that semicolon, by the way.
Every time, is z greater than 75? Sure, z is still 100. Is 100 greater than 75? Yes.
Do this. Yes. Do this. Yes. Do this.
Over and over and over until you've got a ton of outputs that you just have to control-c to stop this. So we need a statement in here that's going to reduce the value of z to make this statement false. Simple one, z equals z minus 1. We run this, it stops.
We have a set number of values, and we're just giving the square root of z. In this, we decrease the value, so now z becomes 99. 99 is greater than 75. 98 is greater than 75 all the way, you can see we get to 81 at some point here, because the square root of 81 is nine, and then eventually we hit a stopping point when z is equal to 76. This will be true one last time. We'll decrease 76 to 75, and then 75 is not greater than 75. That will be false, and it ends. and then anything you want here can add loop ended it's a little reminder for us we run this And we get our little display afterwards because the script keeps on running afterwards.
The last thing I wanted to show you guys was how to make this into a separate function. You're going to end up with very complicated things, very complicated expressions, very complicated mathematical formulas, you know even all these the nested loops, the nested if statements. It becomes easier at a certain point to create a separate.m file to handle all those things and then you can just run those.m files from your main.m file.
Let's create a new script and we're going to use it as a function. MATLAB has a great built-in feature for this. Click the drop down by new and select function. It gives you all the basic structure that you need.
To create a function you're going to start with function and then define what output arguments you want. This should be the name of the function here. and then you're going to add input arguments. All this inside will be using your input arguments to create your output arguments.
In our case we're just going to be running our while loop. Let's take this stuff right here and let's replace it in here. While z is greater than 75, display square root of z.
Yes, we're going to get rid of this line. We don't need to display these things. We just want to reduce it down.
So let's plan for this to be a more general case. So let's have our output be the final z value, z final. And we'll have our input just be z.
Let's call this function reduce z with an underscore in there. And we need to save it as that same name, reduce underscore z dot m. This is where the current folder matters.
We need... this file, this.m file, to be in the same folder as our main script, which I have basics here. That way, these two files can interact with each other because they're in the same current folder. Now for reduceZ, what we'll do is we receive a Z value, and let's say that's Z initial. Let's set Z equal to Z initial.
no output needed, and then while z is greater than z initial, we're going to reduce the value of z, and this will become z final. So actually, no, let's keep this as z for now, and then at the end of everything we'll save z to z final equals z. Okay, so we bring in z. Let's think of how this is going to go through. So if we give an input of 75 like we did before as our argument to this function reduce z, 75 is saved to z while 75 is greater than z initial.
This doesn't work. Let's do this divided by 2. So while 75 is greater than 75 over 2. Then we reduce z every loop until it gets to this point, which will happen because we're reducing it. Eventually we'll get down to, you know, z over 2, and then we'll be final. This is a little bit complicated guys, I know. I'm just trying to show you this function notation, and we'll output z here, and this z final is what we have as our output to our function.
Let's save this. We'll go back to basics. Don't need this anymore. All we need to do is run our function, which we called reduceZ. Let's give it the argument of Z, and we'll see what happens here.
We run this, and we get our answer out to be 50. Don't need this anymore either. Does that make sense to us? We're giving a value of 100. This is the one argument that we're giving to our function.
So the value of 100 is passed to the function reduceZ. We go into reduceZ. Here, Z initial is set to 100. 100 is saved to Z.
Z is 100 here, while 100 is greater than 100 over 2, so while Z is greater than 50, we take Z, which is 100 to start, and we decrease it by 1, so it goes down to 99. Now we're 99. greater than 50. We go again, we reduce, so now it's 98, 97, 96, 95, all the way until z is gonna be what, 51? Z is 51 greater than this. Oh no, 51 will be true, so 51 greater than 50, yes.
Z is reduced down to 50. 50 greater than this, no, false. We end the while loop and then we save 50, which is z. to z final. z final is then our final output for the function and that gives us this answer of 50. I know it's crazy.
It is very hard to get your mind around this. If you're struggling, do not worry. I have entirely separate youtube videos on these topics.
These last ones, these for loops, while loops, and functions, they are challenging. Don't back down. Think of it as a way that you need to push yourself to understand these advanced parts of the programming language.
Question for you. What if I put 75 here? What would be the final answer? Well, think. Eventually, we're going down to the z over 2, that z initial over 2. So it'll be 75 over 2, which would be 37.5.
When z is 38, This will still be true because 38 is greater than will reduce down to 37 and that should be the last loop. So let me run this and 37 is inevitably our answer. Holy cow guys, I think we did it. We covered so many topics in this video.
I'm amazed if you stayed to the end. Kudos to you. This is one of the best beginner crash courses that I could come up with for you guys.
More videos on the channel. This was meant to give you foundations. Now from here, I encourage you to dive into specific topics that you need to do for whatever project or whatever you're just curious about doing in MATLAB. Thank you for watching. Seriously, this channel has been growing because of people like you who are committed to learning programming and I'm committed to helping you learn to program.
Thank you so much for watching. Please like this video, please subscribe, engage on the channel. I answer any single question that you guys want to ask. I'm happy to clarify.
I'm happy to make more videos. Just let me know. I am here to help you excel in your programming experience. Cheers and have a great day.