MATLAB

2. Simple Mathematics

Variable names

You would have noticed that MATLAB gives the result of each calculation the default name ans. This clearly will become confusing and unacceptable when a sequence of commands is executed, especially in an M-file. Hence, you should always give the result a variable name. This variable name can then be used in subsequent calculations in a manner similar to putting a result in the memory of a calculator. The rules for variable names are

  • variable names are case sensitive; crows, Crows, cROWs, CROWS are all different variables
  • variable names can contain up to 63 characters; prideofsouthaustralia is acceptable
  • variable names must start with a letter, followed by a mixture of letters, digits or underscores. Other symbols and spaces are not allowed; x, ABC, item3week1, profit_1999, Pride_of_South_Australia are all acceptable variable names

Type in the following sequence of commands after the prompts on consecutive lines

x=7.231

y1=x+1/x

y2=x-1/x

difference=y1^2-y2^2

Exercise: explain why the answer must be 4 for any initial x. Then use the up-arrow repeatedly to change x to any other non-zero value, find new y1, y2 and demonstrate that difference is always 4.

Note: this continual use of the up-arrow will become unmanageable and very confusing when we have a longer sequence of commands. That is where the use of M-files will become crucial.