MATLAB - Array Multiplication
Array multiplication in MATLAB involves performing operations on arrays of numbers.
Element-wise multiplication is used when you want to multiply corresponding elements of two arrays together. This type of multiplication is denoted using the .* operator.
The arrays being multiplied must have the same dimensions. Each element in the resulting array is obtained by multiplying the corresponding elements from the original arrays.
Syntax
X = A.*B X = times(A,B)
X = A.*B performs array multiplication between A and B by calculating the product of their corresponding elements. It's important to ensure that A and B have either identical sizes or sizes that are compatible for this operation.
The usage of C = times(A,B) as an alternative method to compute A.*B exists, although it's infrequently employed. This approach allows for operator overloading in classes.
Example 1
Multiplying two vectors A and B.
A = [1 2 3] B = [4 5 6] X = A.*B
When you execute the same in matlab command window −
A =
1 2 3
B =
4 5 6
X =
4 10 18
Example 2
Let us try another example by using a matrix of 2x3 as shown below −
A = [1, 2, 3; 4, 5, 6] B = [2, 2, 2; 3, 3, 3] C = A .* B
When you execute the same in matlab command window the output is −
A =
1 2 3
4 5 6
B =
2 2 2
3 3 3
C =
2 4 6
12 15 18
The matrix C is also the same size as of A and B.
Let us now try to make use of the times() method for the above examples we have tried using .*.
Example 3
Multiplying two vectors A and B using the times() method.
A = [1 2 3] B = [4 5 6] X = times(A,B)
When you execute the same in matlab command window −
A =
1 2 3
B =
4 5 6
X =
4 10 18
Example 4
Let us try another example by using a matrix of 2x3 but will multiply them using the times() method.
A = [1, 2, 3; 4, 5, 6] B = [2, 2, 2; 3, 3, 3] C = times(A,B)
When you execute the same in matlab command window −
A =
1 2 3
4 5 6
B =
2 2 2
3 3 3
C =
2 4 6
12 15 18
Multiply Row and Column Vectors
The row vector with dimensions 1-by-3 and the column vector with dimensions 4-by-1 are multiplied in the example below, resulting in the creation of a 4-by-3 matrix.
a = 1:3 b = (1:4)' result_matrix = a .* b
In this example, 'a' is the row vector [1, 2, 3], and 'b' is the column vector . The ' operator is the transpose operator. When applied to a matrix or an array, it flips the rows and columns, effectively transforming rows into columns and columns into rows.
The expression (1:4) generates the row vector [1, 2, 3, 4].Applying the transpose operator ' to the row vector converts it into a column vector −
b =
1
2
3
4
When these vectors are multiplied element-wise, the resulting matrix 'result_matrix' will be −
a = 1 2 3 b = 1 2 3 4 result_matrix = 1 2 3 2 4 6 3 6 9 4 8 12