Skip to main content

Section 8.9 Variable Basics

To complete our lesson on how to use MATLAB as a calculator we need to discuss variables. Luckily, assigning variables in MATLAB is very easy and MATLAB is very forgiving with its variable naming rules. To assign a variable, you simply use the = operator. (Note: you don’t need to type in the >>. From now on I will put the >> in when you should type a command into the command window. Notice how the command window prompt in MATLAB is >>.)
>> csu=1881;
In this case, the variable named csu will be assigned the value 1881 (recall that the semicolon simply suppresses the output to the command window. Try typing the example into MATLAB yourself with and without the semicolon to see it in action!). At this point, you should notice that a new variable csu has been added to the workspace. Now we can use the variable csu in any mathematical operation.
>> csu+19;
You should notice that without the semicolon, 1900 is output to the command window. Sure enough, that is 1881 + 19! The other thing to notice is that if you do not specify a variable to store an operation in, MATLAB will default to storing the value in a variable named ans. You can see this in the workspace. The ans variable is OK, but it is not a safe place to store information. MATLAB will overwrite the ans variable every time an operation is performed that does not include an assignment. Let’s re-try that last operation and this time assign the resultant to a new variable called total.
>> total = csu+19;
When you try this, you should notice a NEW variable named total added to the workspace and that it contains the value 1900. If you have been following along, you should have three variables in your workspace; csu, ans, and total.
The last thing we should mention about variables is the variable naming rules:
  • MATLAB variables must start with a letter
  • After the first letter, other letters, digits, or underscores can follow. No other characters can be used
  • Variables are case sensitive meaning the variable RAMS and rams are NOT the same
  • This is just a guideline but your variable names should be descriptive of the quantity that they are storing

Checkpoint 8.9.1. Variable Name Validity.

Is the following variable name valid or invalid?
>>x7
  • Invalid
  • Incorrect. Variable names in MATLAB may contain letters and numbers as long as they begin with a letter.
  • Valid
  • Correct! x7 is a valid MATLAB variable name because it begins with a letter and contains only letters and numbers.
You have attempted of activities on this page.