0
0
MATLABdata~5 mins

Element-wise operations (.*, ./, .^) in MATLAB

Choose your learning style9 modes available
Introduction
Element-wise operations let you do math on each item in two lists or arrays separately, just like doing the same task on each apple in a basket.
When you want to multiply two lists of numbers, matching each pair one by one.
When you need to divide each number in one list by the matching number in another list.
When you want to raise each number in a list to the power of the matching number in another list.
When working with arrays where you want to apply operations to each element, not the whole array at once.
When you want to avoid matrix multiplication and instead do simple math on each element.
Syntax
MATLAB
C = A .* B
C = A ./ B
C = A .^ B
The dot (.) before the operator means 'element-wise', so it works on each pair of elements.
A and B must be the same size or compatible sizes for these operations to work.
Examples
Multiply each element of A by the matching element of B.
MATLAB
A = [1 2 3];
B = [4 5 6];
C = A .* B;
Divide each element of A by the matching element of B.
MATLAB
A = [10 20 30];
B = [2 4 5];
C = A ./ B;
Raise each element of A to the power of the matching element of B.
MATLAB
A = [2 3 4];
B = [3 2 1];
C = A .^ B;
Sample Program
This program shows how to multiply, divide, and raise elements of two arrays one by one.
MATLAB
A = [1 2 3];
B = [4 5 6];

mult = A .* B;
div = A ./ B;
pow = A .^ B;

fprintf('Multiplication result: ');
fprintf('%d ', mult);
fprintf('\n');

fprintf('Division result: ');
fprintf('%.2f ', div);
fprintf('\n');

fprintf('Power result: ');
fprintf('%d ', pow);
fprintf('\n');
OutputSuccess
Important Notes
If you forget the dot (.) before the operator, MATLAB will try matrix operations and may give errors or wrong results.
Element-wise operations are very useful for working with data arrays where you want to keep things simple and direct.
Summary
Element-wise operators (.*, ./, .^) do math on each pair of elements in arrays.
Use the dot (.) before the operator to tell MATLAB to work element by element.
Make sure arrays are the same size or compatible for element-wise operations.