There are several tricks you should keep in mind when writing our programs. Learn how to speed up scripts by pre-populating matrices.
- [Instructor] Often when we're working with really large data sets, we need to consider the performance of our scripts and functions, so that they don't take a really long time to run. Let's see how we can do that by preallocating space for our matrices and vectors. I'm going to go ahead and close out our break point here. And close letsloop. And let's create a new script. I'll go down here, right-click, new file, script, and I'll call this performance. Let's open that up.
And in the comment here, I'll say preallocate some memory. So just as an example of when we need to deal with this, let's create a for loop here. We'll say for, we'll have i go from one to one million. And in this, let's have a vector, m, and the ith place in m will just be equal to i. So we'll create this vector that'll be a million elements long and each of the elements in it will go from one to one million.
Let's end that. And we can already see a little warning under here if we mouse over that. The variable m appears to change size on every loop iteration. Consider preallocating for speed. MATLAB already knows it's bad that we're changing the size of m each time through this for loop. But for now, let's see how long it takes to build this vector. MATLAB has a fun pair of functions called tic and toc that will tell us how much elapsed time has passed for the code in between them. So let's put that in here.
And let's run our script. So if we look down here in the command window, we see that the elapsed time to build this large vector was almost 67 milliseconds. So now instead, let's preallocate our vector. So we'll say, m is equal to, and then let's use that function zeros. This will build our vector of all zeros and then we'll replace them in our for loop. We want our vector to be one by one million elements.
So this should speed up our loop quite a bit. Let's go ahead and run it again. There we go. So we see that our elapsed time is now almost eight milliseconds, down from almost 67 milliseconds. So we saved quite a bit of time by preallocating our memory in this wave. So keep this in mind when you're working with large data sets. It can really save you a lot of time.
- Creating MATLAB variables
- Working with matrix and scalar operations
- Using if statements and loops
- Creating functions
- Importing data
- Building basic plots and 3D plots
- Working with images
- Creating Simulink models