Time for action - working with precedence rules
1. Let us see an example:
octave:117> A*y + a ans = 2.5000 -3.0000 1.7500
Here, Octave first performs the matrix multiplication between A and y, and then adds a to that result. We say that multiplication has higher precedence than addition.
2. Let us try two other examples:
octave:118> A*y.^2 ans = 4.2500 -18.5000 2.3750 octave:119> (A*y).^2 ans = 0.2500 25.0000 0.0625
What just happened?
In command 118, because the .^
operator has higher precedence than *
, Octave first calculates element-wise power operation y.^2
, and then performs the matrix multiplication. In command 190, by applying parenthesis, we can perform the matrix multiplication first, and then do the power operation on the resulting vector.
Note
The precedence rules are given below for the operators that we have discussed in this chapter:
When in doubt, you should always use parenthesis to ensure that Octave performs the computations in the order that you want.