How to Use Element Wise Operations in MATLAB
In MATLAB, element wise operations are done by placing a dot
. before the operator, like .* for multiplication or ./ for division. This tells MATLAB to apply the operation to each element of arrays or matrices individually.Syntax
Element wise operations use a dot . before the operator to apply the operation to each element of arrays or matrices.
A .* B: element wise multiplicationA ./ B: element wise divisionA .^ B: element wise powerA + BandA - Bwork element wise by default
matlab
C = A .* B; % Multiply each element of A by corresponding element of B
D = A ./ B; % Divide each element of A by corresponding element of B
E = A .^ 2; % Square each element of AExample
This example shows element wise multiplication, division, and power on two arrays.
matlab
A = [1, 2, 3]; B = [4, 5, 6]; C = A .* B; % Element wise multiplication D = A ./ B; % Element wise division E = A .^ 2; % Element wise square disp('C = '), disp(C) disp('D = '), disp(D) disp('E = '), disp(E)
Output
C =
4 10 18
D =
0.2500 0.4000 0.5000
E =
1 4 9
Common Pitfalls
One common mistake is forgetting the dot before the operator, which causes MATLAB to try matrix multiplication or division instead of element wise. This leads to errors or unexpected results if the dimensions don't match.
For example, A * B tries matrix multiplication, but A .* B multiplies elements one by one.
matlab
A = [1, 2, 3]; B = [4, 5, 6]; % Wrong: matrix multiplication (error if sizes don't match) % C = A * B; % This will error because A is 1x3 and B is 1x3 % Right: element wise multiplication C = A .* B; disp(C)
Output
4 10 18
Quick Reference
| Operation | Element Wise Operator | Description |
|---|---|---|
| Multiplication | .* | Multiply each element of arrays |
| Division | ./ | Divide each element of arrays |
| Power | .^ | Raise each element to a power |
| Addition | + | Add elements (works element wise by default) |
| Subtraction | - | Subtract elements (works element wise by default) |
Key Takeaways
Use a dot before operators like * and / to perform element wise operations in MATLAB.
Element wise operators apply the operation to each corresponding element of arrays or matrices.
For addition and subtraction, MATLAB applies element wise operations by default.
Forgetting the dot can cause matrix operations or errors if dimensions don't match.
Always check array sizes to ensure element wise operations work as expected.