0
0
MatlabHow-ToBeginner ยท 3 min read

How to Add Matrices in MATLAB: Syntax and Examples

To add matrices in MATLAB, use the + operator between two matrices of the same size. For example, C = A + B; adds matrices A and B element-wise to produce C.
๐Ÿ“

Syntax

Matrix addition in MATLAB uses the + operator between two matrices of the same size. Both matrices must have the same number of rows and columns.

  • C = A + B; adds matrices A and B element-wise.
  • A and B must be the same size.
  • C is the resulting matrix after addition.
matlab
C = A + B;
๐Ÿ’ป

Example

This example shows how to add two 2x2 matrices in MATLAB and display the result.

matlab
A = [1 2; 3 4];
B = [5 6; 7 8];
C = A + B;
disp(C);
Output
6 8 10 12
โš ๏ธ

Common Pitfalls

Common mistakes when adding matrices in MATLAB include:

  • Trying to add matrices of different sizes, which causes an error.
  • Confusing element-wise addition with matrix multiplication.

Always check that matrices have the same dimensions before adding.

matlab
A = [1 2 3; 4 5 6];
B = [7 8; 9 10];

% This will cause an error because sizes differ
% C = A + B;

% Correct way: use matrices of the same size
B_correct = [7 8 9; 10 11 12];
C = A + B_correct;
disp(C);
Output
8 10 12 14 16 18
๐Ÿ“Š

Quick Reference

Remember these key points for matrix addition in MATLAB:

  • Use + operator for element-wise addition.
  • Matrices must be the same size.
  • Result is a matrix of the same size.
โœ…

Key Takeaways

Use the + operator to add two matrices element-wise in MATLAB.
Both matrices must have the same dimensions to add them.
Adding matrices of different sizes causes an error.
The result of addition is a matrix of the same size.
Check matrix sizes before adding to avoid errors.