How to Use .^ Operator in MATLAB for Element-wise Power
In MATLAB, the
.^ operator performs element-wise power, raising each element of an array to the specified power individually. Use A .^ B where A and B are arrays or scalars of compatible sizes to compute powers element by element.Syntax
The syntax for element-wise power in MATLAB is A .^ B.
A: Base array or scalar..^: Element-wise power operator.B: Exponent array or scalar, must be compatible in size withA.
This operator raises each element of A to the corresponding power in B.
matlab
C = A .^ B;
Example
This example shows how to square each element of an array and how to raise elements to different powers.
matlab
A = [1, 2, 3; 4, 5, 6]; B = 2; % scalar exponent C = A .^ B; D = [1, 2, 3; 2, 3, 4]; % element-wise exponents E = A .^ D; C E
Output
C =
1 4 9
16 25 36
E =
1 4 27
16 125 1296
Common Pitfalls
One common mistake is using ^ instead of .^ when working with arrays. The ^ operator performs matrix power, which requires a square matrix and does not operate element-wise.
Another pitfall is mismatched array sizes for A and B when both are arrays. They must be the same size or compatible for broadcasting.
matlab
A = [1, 2; 3, 4]; B = [2, 3; 4, 5]; % Wrong: matrix power (only for square matrices) % C_wrong = A ^ B; % This will cause an error % Correct: element-wise power C_right = A .^ B;
Output
C_right =
1 8
81 1024
Quick Reference
| Operator | Description | Example |
|---|---|---|
| .^ | Element-wise power | A .^ 2 squares each element of A |
| ^ | Matrix power (square matrices only) | A ^ 2 multiplies A by itself |
| .* | Element-wise multiplication | A .* B multiplies elements of A and B |
| * | Matrix multiplication | A * B multiplies matrices A and B |
Key Takeaways
Use
.^ to raise each element of an array to a power individually in MATLAB.The
^ operator is for matrix power and requires square matrices.Ensure arrays used with
.^ have compatible sizes or use scalars.Element-wise operations are essential for array-by-array calculations in MATLAB.