In today’s lesson, we are going to be discussing the following topics:
1. What is a variable? How is it created?
2. Using Variables in Problems
3. Overwriting Variables
What is a Variable?
A variable is a word or letter that stores a value (a number) within it. This is so we can use it again later on without typing out all the numbers again. This is the syntax (the rules) for creating a variable:
Variable name = a value (or an expression)
Here are some specific examples below. I have named the variables “x,” “variable,” and “cat,” “name_52,” and “name_4,” just to show that you can name them anything. Note that the left side of the equals sign needs to start with a letter, and then it’s fine if there’s numbers after it. See below in red when I tried to use “4_name” I got an error, but “name_4” worked. It also gave error when I tried to use just “42.” The right side of the equals sign can be a mix of numbers and letters (of which an example is given under the “Overwriting Variables” heading at the bottom of the page).
All you do to create a variable is type it into the command window, like this:
Then hit enter and MATLAB stores it, and outputs the same thing again. Now it is stored in the workspace (check out this lesson if you don’t know what the Workspace, Command Window, and other terms are).
Note that if we write a numerical expression without a variable, MATLAB automatically stores it in a variable called “ans.” See below how I just wrote ‘5’ and then MATLAB stored it into a variable “ans.” So now “ans” is equal to 5.
Using Variables in Problems
Here is an example of how variables can be used once they’re created. Let’s use the variable “ans” because now that equals 5. We can use “ans” in an equation like “ans + 3” and it does “5+3.”
Overwriting Variables
Say we don’t want to store the number 5 in the variable “ans” anymore. Instead, we want to store it in a variable “a.” So we can overwrite it, which means we just make the same variable again, and the newest variable that equals 5 will be stored.
Overwriting a variable is when you want the same variable to store a different number. Check out this example below. “a” does not equal 5 anymore, because I overwrote it so now it equals 6:
Now, you can also use letters as well as numbers on the right side of the equals sign. For example, if I code that a=5. Then instead of being 5, I want “a” to be 8. So I can either put “a=8” or I can put “a=a+3.” Because MATLAB will store the most updated expression you give the variable, “a” will equal “a+3.” Because originally a=5, it will take 5+3 to store a=8. Take a look below:
It doesn’t only have to be the same variable you’re overwriting either. Say I have a=5 and b=3. If I want to overwrite “b” to instead be the sum of a+3 for example, I can do that. So now a=5, a+3 will make b=8: