MATLAB as a Calculator
Calculations in MATLAB
The following commands illustrate the order of priority when evaluating expressions.
Before typing each command into your Command Window, think about what you expect the answer to be. If the output differs from your expected answer, figure out why. > Type in the following commands, pressing Enter after each one. 5*2+3 3+5*2 > What if instead, we want to add 3 to 5 and then multiply the result by 2? We can use brackets to change the order of evaluation as MATLAB will evaluate the contents of each bracket pair first. > Type in the following line of code: (3+5)*2 |
Coding tip: Many students have troubles matching bracket pairs. Experienced MATLAB users reduce these errors by 1. typing both brackets ( ), 2. then using the back arrow key ← to move back and fill in the bracket contents (3+5). |
> The following code is not valid. Type it in, press Enter, then read the error message and change the code so that it works (note the vertical line pointing to the first error). 2(3-5) |
Coding tip: The up-arrow key ↑ on the keyboard will recall a previous line for you to edit. |
> Type in the following lines to figure out what the hat ^ key represents. 3^2 3^3 > Figure out the answers you would expect for the following two lines of code and then type them in to verify your answer. 9-3^2 81/3^2 |