Variables

Naming variables

The following commands illustrate the order of priority when evaluating expressions.

A love-struck engineer specialising in planning the foundations of a building wrote the following code to calculate the area of a rectangle.

> Determine what each variable represents and then rename the variables to write the new code in MATLAB with meaningful variable names.

dinner = 4

nice = 7

roses = dinner*nice

wink Some important rules for variable names are:

  1. They are case sensitive: nice, NICE,NiCe and NicE are all different.
  2. They can have a length of up to 63 characters Pachycephalosaurus is a valid variable name (although it is quite frustrating to type).
  3. They must start with a letter, followed by any combination of letters, numbers and underscores. For example, week1, week1_prac, MATLAB_prac_1_is_fun, x are all valid variable names.
  4. There are some reserved words that can’t be used as a variable name, i.e. help, pi, sin, pretty, etc.
  5. clear statements are used to delete the values of previous variables. clear all deletes all values, whereas clear <variable name> just deletes the variable you nominate. It is a good programming practice to start your code with command clear all.

The preferred naming convention is to capitalise the start of each new word, as in ThisIsALongVariable however some people prefer to separate words with underscores, as in this_is_a_long_variable.