There are a few good reasons to use a script. When you’re writing more than a couple of lines of code, it might take a few tries to get everything right. Putting your code in a script makes it easier to edit than typing it at the prompt. Likewise, if you’re running a script repeatedly, it’s much faster to type the name of the script than to retype the code! And you might be able to reuse a script from one project to the next, saving you considerable time across projects.
But the great power of scripts comes with great responsibility: you have to make sure that the code you are running is the code you think you are running. Whenever you start a new script, start with something simple, like
x = 5, that produces a visible effect. Then run your script and confirm that you get what you expect. When you type the name of a script, MATLAB searches for the script in a search path, which is a sequence of folders. If it doesn’t find the script in the first folder, it searches the second, and so on. If you have scripts with the same name in different folders, you could be looking at one version and running another.
If the code you are running is not the code you are looking at, you’ll find debugging a frustrating exercise! So it’s no surprise that this is the Third Theorem of Debugging:
Be sure that the code you are running is the code you think you are running.
Now that you’ve seen how to write a script, let’s use one to do something a little more complicated.