MATLAB Tutorial 4 - A Look at Creating and Calling Functions!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
oh hey there this is Jake and welcome to the fourth of our series of short tutorials to try to get you guys into the mood for using MATLAB and some of the nuances and useful features that we like to take advantage of in 3eo 4 so today we're going to do something a little different than what we've been doing recently and you'll see that I've started a new file I've called it T for main it's over here and it's also in my working directory right there and now the reason I called a T for main instead of T 4 as opposed to T 3 and T 2 like I had before is because today we're going to learn about implementing functions so there are a lot of functions in MATLAB for example in the last few episodes we've had the plot and zeros and Rand and all these different functions that are already built into MATLAB but what we're going to do today is make some of our own so I'm going to have some different file names all in the same directory what we're going to do is make one not exactly long but like one code that's going to calculate some sign and Coast functions and then plot the results on a nice pretty graph and then what we're going to do is we're going to take all of the jargon and junk lines out of our main code and put them into some nice simple functions and our main code will look nice and compressed and easy to read from that point on so we don't further adieu let's get going you guys will see how things work as we proceed mainly we want to take a look at the syntax for functions and that sort of thing but before we get started we are going to have to start with are critical three lines for our code which are what blows all clear variables and CLC so let's let's get those in there right away because we don't want to forget I can't stress enough the importance of this kind of just kind of structure or just you know just maintain some sort of routine I guess when you're when you're making your code try to get those guys in there because like it's just it always gets so annoying the last thing you wanna do is overwrite your own variables so the second time you try to run your code it doesn't work it's just not good for anybody especially your TAS so we're going to calculate some random sign and Coast functions here I'll just make them up as we go and what we're going to need for this is an X range so let's see no plot this is going to be between I don't know let's say minus five in steps of 0.1 and five kind of like kind of like this so you know that's going to be minus PI and a half zero point one sup two like PI and a half let's sort of range we'll see what ends up happening there and now I'm going to get yelled at by MATLAB for having these brackets because I'd like to put the brackets around my vectors but I guess we just want to make sure that we don't have anything we have that green square up there so if I run that and I call it X prime so it's easy to look at you can see that I go from minus five to five so that's perfect that's exactly what we need everything is working correctly so now let's let's make a calculation section here so I'm going to make these two little areas so let's calculate two different functions one a sine function one a neck the coast function rather so let's call the sine run Y so we're going to do y equals two times sine of X minus one and just shift it a little bit there now bear in mind that I don't need to dot multiplier here even though X is a vector and sign is of X is going to create a vector as well and that's because remember this is just scalar multiplication there's nothing to stop me from putting the dot there it's just not going to actually do anything right now so I'm just going to go ahead and keep it away so there we go out to Y and then let's do Z and we'll call Zed you know 1.5 times coasts X and let's shift that up by a factor of two so now we've got our two two functions there let's take this from that make sure we don't have any issues call it Y Prime just as an example there you go we've got our information there we've got minuses and pluses which is good because it is a sine function after all and now what if I were to see what it looks like well one really cool thing you can do well it's not really cool it's kind of basic really but if you just want to see what the shape of what you're looking at is just doing a basic plot in your command window over here and throwing in in this case why don't even need to give it any X data it'll just numerate all the entries in Y from 1 to 100 one in this case and what will happen is you'll just get this nice basic kind of ugly looking plot but you can just kind of see what the shape of this thing is going to be and I said that there's a hundred and one entries because over here if we were to do the length of Y for example we should find that we have 101 entries because that is after all the length of X as you can see right there so let's get rid of that now what we want to do next so this is going to end up being one of our functions I'll just drop that right now but what we're going to end up doing first is let's plot that information so that we can you know make a nice looking plot and then we'll put this into a function and then all the plotting stuff into a function so our main file is literally going to be three lines it's going to be not including these it's going to be this guy and then a thing that calls our function and then a thing that calls our other function it's just going to be nice and short and sweet it'll look pretty sweet so the first line that I'm going to call up here is figure now this is optional what happens if I run this with just figure I'm going to get a box that comes up it's called figure one and it doesn't really do much except for just make a new window so it ensures that you got a new window I like to throw it in there every once in a while just to ensure when I'm running through my own code I notice okay I'm making a new new graph right here that's what that's going to be so let's throw in a comment and graph exclamation mark one one one excavation mark-- one explanation hey beautiful so then also let's do the hold on command because we know that we're going to have to plot y and z or at least i would like to put y&z on the same set of axes so I'm going to want to do that and then we'll go ahead and do the hold off command down here too because I don't want to forget to turn that off lest we end up plotting something else on the same axis which will you know potentially end up looking like garbage and then let's go ahead and plot it so you know we'll throw in our X data and our Y data for this we're just doing the sine command right now and in single quotes I can choose what color of line I want the defaults blue by the way as you noticed on our original just plot basic command we did but I'm going to add in a couple of options instead of just R for red I'm going to say our line and O so the O means circle markers and the dash means I want to have a line in between them all and then let's do one more option line width as we did with the last time because I find the default line width to be very thin and gross and we'll make it a two instead of one so a couple of things I want to point out I thoroughly encourage you guys to check out the doc plot command or of course doc anything command to check out all the different types of options that you can do when you're making graphs because there are tons of different options and like I mentioned I think in the second or third tutorial going through that that document and just taking a look at the examples and I'm showing or taking a look at their example lines of code that they typed in and then actually seeing what the result of that is kind of really gives you a feel for what you can do to make your graphs look better so like you can do things like change the marker face color make it there or not the marker edge color all all the basic things that you can do basically in Microsoft Excel when messing around with your plots there you can do in MATLAB as well and it's a lot less time-consuming than you might imagine you might say well I don't want to plot or type all this stuff in but you know by the end of the day once you get used to it and you can start to copy and paste your templates or use functions for your templates in MATLAB it gets right down to the same amount of time that it takes to click around Microsoft Excel to try to get that stuff and I'm a huge fan of Microsoft Excel so I have no bias toward MATLAB in that regard at all but you just need to kind of open your mind to the different options so anyway just a little brainwashing activity there I'm going to copy that line down I'm going to go with the Zed data now which is our cosine and I'll make these ones black so that's K for black and then I'm going to also have a line with circle markers and then I'm going to have that line with its two and then let's put in our axes titles so let's call the x axis X and the y axis we'll call Y and zip just like that and then let's put in a title the title can be plot of sine and cosine functions and then we'll throw in why not a legend so if you remember from last time the legend you put in single quotes the name of whatever line in the order that they were plotted so in this case the first one is the sine function so why don't I just go ahead and put in two sine of X minus one because it's just going to be a string and that's just going to be a nice little equation up there and then this one I can have like 1.5 cossacks plus t because that's what we had and then let's throw in something I'm forgetting my semicolons here with plotting command semicolons usually aren't critical but it's just good practice it never hurts let's make sure that the box is on on the plot because I like that and let's do legend let's do box off because I don't like the box on the legend personal personal stuff and then we'll delete some extra lines here and it should be it so let's see what happens we run this hopefully we have no mistakes no we got no mistakes I bring in our plot over here you can see that we've got 1.5 coasts X plus 2 and 2 sine X minus 1 so there you go I can go ahead and maximize that take a look at that sort of thing and then you know the way that we've written this function or not function so I code like if I wanted to change this to be 0.01 instead of 0.1 and get a whole bunch more points it's as easy as just changing that and then clicking run you can see there we've got a ton more points in there they are so close together that you can almost not even tell so they're you know those are the points much closer together so they're anywhere and you can change the size of the font size of all this stuff as well as you're going along I'll let you guys take a look at that in your own time because it's not entirely important for this so that's our finished code and you know it's only like say 29 29 lines including a few comments here and there so that's not that bad pretty basic but let's try to make it a little bit shorter so what I'm going to do is I'm going to collapse this guy into a function so functions in MATLAB are they're not terribly difficult as long as you just get used to how they're called so there's usually two ends of it the first end is the actual function that you write and the second end of it is the phone where you call the function so here we go I'm going to make a new function a new script up here so new it's untitled too so here's the first line that you always put into a function so you can put some comments and then I can say like you know function that calculates X or sorry not XY and Z because those don't count but the first line of the code has to be the word function and as soon as you do that when you save this it's not going to save it as an m5 it's going to save it it's going to have a little FX over here in your work folder which means that it recognizes this as a function so here's the syntax is always function and then variables it's going to calculate and then equals and then the name of the function so I'm going to call this t4 you know sign coasts you get to make this up right and then whatever the function is going to be given in order to do its calculation so in this case I'm going to be given X so out here you see that I'm passing in X so I'm going to call it X up here now one thing about functions that you could you know might want to know is that inside a function unless you're dealing with global variables which you should almost never do what will end up happening is that the variables in this function have their own name and they don't care about the rest of them so I could call this X and I could pass in X past the enemies like put it in the square are the curly brackets there but in here you know I may as well call it bananas or something like that because it doesn't really matter so I'll just show you what I mean so and then to end a function you just want to put end so now here's the thing you should never run a function if I try to run this I'm going to get some bunch of errors because you should never run a function from this command window which you can only do is call a function either in your command line or in a main file that's why I call this one the main this is the one we're going to plus press the play button and functions you can't really press the play button so what I'm going to do is I'm going to save this and now it's going to open up now here's something very critical what you have to always do is save the function in the same directory as your main file so there's t for main right there and then also you have to save it exactly as you wrote the name right here so I called a t for sign COSO it's going to give me the default T for sign Coast and then save it just like that and now if you ever save it as something different you're going to get a warning here that it doesn't recognize this function and sometimes that happens like say you want to going through and you change it to be T for sine Coast - and then you re save it but then it saved as T for sine Coast you don't have to save as and and fix that up and it's going to give you this morning it's not known to see it's not known to Matt Matt by that name so I'm gonna have to get rid of that so now in in where these export variables are I'm really just going to export y&z so in square brackets you put in what you're going to export if you leave the square brackets empty it doesn't export anything which is like possible a lot of the time and which will end up happening with our plot code actually but if you are going to export variables then you have to type them in with a comma in between them in here and it's going to say that we're not setting these values but as we type the equations in it's going to go ahead and it's going to recognize what we're doing so now what we can pretty much do is take these two equations right here because y&z are going to be calculated we're going to copy them and put them right in here and now the only thing we need to do now is that this isn't a function of X it's a function of bananas so we may as well put bananas in here well not me as well we have to put the nails in there if we put in X it's going to come back and say I don't know what X is so here's an example if I press the Run button it's not going to work it's going to say not enough input arguments because I need to put in bananas into this function and if I just run it it doesn't know what that is so what I'm going to have to do is pass that value in somewhere else so what I'm going to do is pass it in right here so that's the defining the function and now calling function it's going to export these two variables y&z now I don't have to call them y&z out here but I'm going to so y&z and I'm going to say equals and then I'm going to call my function just like I called say the zeros function I'm going to call mine so I'm going to t4 sine Coast and then I have to pass in a value so this thing considers it to be called bananas but this thing I'm going to pass you an X because X is what I've got right here and as soon as X goes into this thing the function reads it in as being that bananas function I really don't know why I use bananas by the way we're not function rather but variable it's going to just say oh that's what bananas is and then it's going to pass that value with it so I may as well just have X's here here and here but the point of having this other word in here is that it just doesn't matter what you do so I'm going to go ahead and do that there you go and now what we've done is we've taken those two lines we've collapse them into one line if I run this what will end up happening is we get the exact same result as we had before so what we end up doing is getting by and Zed just like we calculated individually but we calculated them in our main file in one line and then I'm in our one line it went in here it said here's X came in to this thing it said there's X so calculate Y calculate X now for Z rather give y&z back and then it gave y&z back right there and then it continued on so there you go we used a function so that so the last thing that we're going to do is say make a plotting command so let's do let's get rid of this whole thing right here so new and then we're going to call this function and then I'm going to call it alright it's got no outputs and we're going to say those no outputs are equal to T for T for what and then and so now I'm going to save this it's going to come up as t4 plot that's fine let's do that and t4 plot is actually a function of I'm going to forgot the inputs but it's we're going to need x y&z basically because all of this stuff is going to require x y&z everything else we kind of just have typed in there so it's going to require x and y NZ in that order so the order that you write them here is the order that they're going to be using there and so the order that you pass them into a function just like with there's X if it had more than one input argument say x and y I got to pass them in in the correct order so there you go that's going to happen it's going to warn me that I don't use any of those but we're going to fix that very soon so now what I can do is just copy this guy right out copy it right in there that whole thing get rid of some extra lines save that it's going to recognize that we got x y&z in here now because here they are so you can see them all floating around like that and then I'm going to comment this whole thing out because I don't want it to do anything anymore and then I'm just going to call my plot function so since there's no outputs I don't have to have anything equal to it so I'm just going to have t4 equals our sorry for underscore plot I'm going to pass it x and Y and Zed civically and that is basically it so I'm not even going to throw in a line down here I'm going to make it print out ran the plotting functions so we know that it's going to print this out if it gets into this plotting function properly so I'm going to go back here to my main file close that guy off and now if I run this what is going to happen we ran the plotting function and we have the exact same graph that we have before so at the end of the day if I wanted to I could just delete all these comments that I don't need and what you end up having here is a main code of one to three lines and all the nonsense that you don't want to have to look at and like all this purple text in here that nobody likes let's throw in a new line after that I just realized that you need a new line there see but anyway save that up that will work and we are in good shape there we go and we have made two functions we've condensed our main code it was very successful one thing that I want to mention is every time you change a function so let's say I also want to print off yay because I'm a little excited that I've been doing this this cool stuff now if I run this it's not going to print that out now why you see the little star up here what MATLAB does in the main file when you press run it'll automatically save your file and run it but if you have a function and you have not saved that function since you've last changed it which is what that little star means which I didn't do there then the function as it's called the main file doesn't get automatically saved and you're going to not have that work so sometimes if you adjust a function and it's not doing what you think may be one of the troubleshooting causes you can go back and make sure that you've saved it so now that I've saved it I press run and now I get an error my first error of all these tutorials and that's just because I mistyped F print I missed the F on the end there so now if I save that and I run this I'm going to get yay and then over here I've got my graph as it popped up and we're in good shape anyway so I hope you learned a little something about making functions there and and that was useful to you if it wasn't useful to you I'm really sorry that I just consumed the last 22 or so minutes of your life but anyway I think we're going to do one more tutorial hmm well it'll be number five I guess and what I'm going to take a look at is like troubleshooting inserting breakpoints that's what those nice little red circles there are we're going to talk about putting in breakpoints and trying to troubleshoot problems in your code and then some you know common mistakes that I hate but on top of that you know they're inevitable and hopefully maybe you guys will that might get some troubleshooting expertise so that you're able to go ahead and and find those mistakes without banging your head against the wall so as usual thanks for watching and I hope this was helpful again any feedback just go ahead and send me an email and order to talk to me and tutorial or something like that and I'll see you next time all right have a good one
Info
Channel: Numerical Methods ChE McMaster
Views: 228,659
Rating: 4.818182 out of 5
Keywords: MATLAB (Programming Language)
Id: Gf89qyP0BxY
Channel Id: undefined
Length: 21min 49sec (1309 seconds)
Published: Tue Aug 27 2013
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.