How to Multiply Matrices in MATLAB: Syntax and Examples
In MATLAB, you multiply matrices using the
* operator between two matrices. Both matrices must have compatible sizes, where the number of columns in the first matrix equals the number of rows in the second matrix.Syntax
The basic syntax for matrix multiplication in MATLAB is:
C = A * B;Here, A and B are matrices. The result C is the product matrix. The number of columns in A must match the number of rows in B for multiplication to work.
matlab
C = A * B;
Example
This example shows how to multiply two matrices A and B in MATLAB and display the result.
matlab
A = [1 2 3; 4 5 6]; B = [7 8; 9 10; 11 12]; C = A * B; disp(C);
Output
58 64
139 154
Common Pitfalls
One common mistake is trying to multiply matrices with incompatible sizes. For example, if A is 2x3 and B is 2x2, multiplication A * B will cause an error because the number of columns in A (3) does not equal the number of rows in B (2).
Also, using element-wise multiplication .* instead of matrix multiplication * is a frequent confusion.
matlab
A = [1 2 3; 4 5 6]; B = [7 8; 9 10]; % Wrong: incompatible sizes % C = A * B; % This will error % Correct: transpose B or adjust sizes B_correct = [7 8; 9 10; 11 12]; C = A * B_correct;
Quick Reference
| Operation | Syntax | Description |
|---|---|---|
| Matrix multiplication | C = A * B | Multiply matrices A and B with compatible sizes |
| Element-wise multiplication | C = A .* B | Multiply each element of A by corresponding element of B |
| Matrix size check | size(A,2) == size(B,1) | Check if multiplication is possible |
Key Takeaways
Use the * operator to multiply matrices in MATLAB.
Ensure the number of columns in the first matrix equals the number of rows in the second.
Element-wise multiplication uses .* and is different from matrix multiplication.
Check matrix sizes before multiplying to avoid errors.
Use disp() to display the resulting matrix after multiplication.