2.6. Basic Arithmetic and Elementwise Operations
Table of Contents
Arithmetic in MATLAB
In MATLAB, arithmetic is usually performed on entire arrays at once. Even if you start with single numbers, it is important to understand how these same operators behave when you work with vectors and matrices.
This chapter introduces the basic arithmetic operators, then shows what elementwise operations are and how they differ from matrix operations. You will use these ideas constantly in later chapters.
Basic arithmetic with scalars
A scalar is a single number, such as 3 or -1.5. You can type arithmetic expressions directly in the Command Window and MATLAB immediately evaluates them. The basic operators are:
+ for addition.
- for subtraction and for unary minus.
* for multiplication.
/ for right division.
\ for left division.
^ for exponentiation.
For example:
2 + 5
10 - 3
4 * 7
9 / 2
2^3
-5MATLAB respects the usual precedence rules. Exponentiation is evaluated first, then multiplication and division, then addition and subtraction. Parentheses control the order explicitly. The following three results are different:
2 + 3 * 4 % 2 + (3*4) = 14
(2 + 3) * 4 % 5*4 = 20
2^(3*2) % 2^6 = 64You can also combine scalars with arrays. When you do this, MATLAB usually applies the scalar to each element of the array. This is one of the most useful features of MATLAB and is discussed in more detail below.
Matrix operations versus elementwise operations
MATLAB is built around linear algebra, so many operators have a matrix algebra meaning when both operands are vectors or matrices.
For example, if A and B are matrices of compatible sizes, the operator performs matrix multiplication, not term by term multiplication. In contrast, the operator . performs elementwise multiplication, that is, it multiplies entries in matching positions.
The same idea applies to division and powers. There is a matrix version and an elementwise version of several operators.
Matrix operators:
* matrix multiplication.
/ matrix right division.
\ matrix left division.
^ matrix power.
Elementwise operators:
.* elementwise multiplication.
./ elementwise right division.
.\ elementwise left division.
. ^ elementwise power.
The dot in the elementwise operators is crucial. Without the dot, MATLAB interprets the expression as a matrix operation and expects the sizes of the operands to satisfy matrix algebra rules.
The linear algebra meaning of *, /, \, and ^ is covered in more detail in the linear algebra chapter. Here, the focus is on recognizing when you want elementwise behavior and how to write it.
Elementwise arithmetic with vectors and matrices
Elementwise operations act on corresponding entries of two arrays. The arrays must be the same size, or one of them must be a scalar. In the simplest case, consider two vectors of the same length:
a = [1 2 3];
b = [4 5 6];
c = a + b % [1+4 2+5 3+6]
d = a - b % [1-4 2-5 3-6]
e = a .* b % [1*4 2*5 3*6]
f = a ./ b % [1/4 2/5 3/6]
g = a .^ 2 % [1^2 2^2 3^2]
Addition and subtraction always work elementwise for arrays of the same size, so there is no .+ or .- operator. For multiplication, division, and power, you must use the dot form when you mean elementwise behavior.
The result of an elementwise operation has the same size as the input arrays. If A and B are both 3x3 matrices, then A + B, A .* B, and A .^ 2 are all 3x3.
If you accidentally write A B when you meant A . B, MATLAB tries to do matrix multiplication. If the sizes are not suitable for matrix multiplication, you will get an error. If they are suitable, MATLAB computes something different from what you probably intended.
Using scalars with arrays
A very common pattern is to combine a scalar with an array. In such expressions MATLAB automatically applies the operation elementwise. You do not need a dot when one operand is a scalar.
For example:
A = [1 2 3; 4 5 6];
B = A + 10 % adds 10 to every element
C = 2 * A % multiplies every element by 2
D = A / 10 % divides every element by 10
E = A.^2 % still need dot for power because both operands are arrays
The last example shows an important exception. The power operator has special matrix meanings, even with a scalar exponent. To make sure you get elementwise powers, always use . ^ when the base is an array. Without the dot, A^2 attempts a matrix power, which only makes sense for square matrices and does not square individual entries.
In summary, when you see a scalar combined with an array using +, -, *, /, or \, you get elementwise behavior automatically. For exponentiation with arrays, use . ^.
Combining arithmetic and functions
MATLAB provides many mathematical functions that operate elementwise on arrays by default. These include square root sqrt, absolute value abs, exponential exp, logarithms log and log10, and many others.
When you call such a function with an array input, the function is applied to each element separately, and the result has the same size as the input. Arithmetic operators and functions combine naturally:
x = 0:0.5:5;
y = exp(-x) .* sin(x) + 1;
z = (x.^2 + 3*x + 2) ./ (x + 1);
In the expression for y, the function exp and sin both act elementwise on the vector x. The multiplication is written .* to match the elementwise behavior. In the expression for z, the addition and subtraction are automatically elementwise, while the power and division use . ^ and ./ because x is a vector.
It is common to mix arithmetic and functions in a single expression. The rules are the same: respect operator precedence, use parentheses when needed, and remember to use the dot versions of operators when operating on arrays entry by entry.
Common size and broadcasting behavior
Elementwise operations require that the arrays have compatible sizes. In the simplest case this means they are exactly the same size, or one is a scalar. MATLAB can also automatically expand certain dimensions so that a row vector and a column vector, or a smaller array, can be combined without manual replication. This is sometimes called implicit expansion or broadcasting.
For example:
row = [1 2 3]; % 1x3
col = [10; 20; 30]; % 3x1
M = col + row
In this case MATLAB forms a 3x3 matrix where each element is the sum of one entry from col and one entry from row. The 3x1 and 1x3 sizes are compatible for implicit expansion. Each is conceptually expanded to 3x3 during the calculation.
The same behavior appears in elementwise operations like .*, ./, and . ^ when the sizes are compatible in this way. If sizes are not compatible, MATLAB reports an error describing that the arrays have mismatched dimensions.
You do not need to memorize all the rules, but you should recognize that MATLAB often lets you combine vectors and matrices of different but related sizes without manual loops or replication.
Integer arithmetic and overflow behavior
If you work only with default numeric values, MATLAB uses double precision floating point numbers, which can represent very large and very small values. When you work with integer arrays, arithmetic is still allowed, but the behavior at the limits is different.
With integer types, if an operation would produce a value outside the range of the integer type, MATLAB saturates the result at the nearest representable value. For example, for an unsigned 8 bit integer uint8, the range is from 0 to 255. If you add two uint8 values and the true sum is greater than 255, the stored result is 255.
For instance:
a = uint8(250);
b = uint8(20);
c = a + b % result is 255, not 270Subtraction behaves similarly at the lower bound. If the true result would be negative, it is stored as 0 in an unsigned integer type.
Elementwise operators like .*, ./, and . ^ work with integer arrays but are subject to the same range limitations. If the result of an operation lies outside the integer range, it will saturate at the bounds.
When you need precise mathematical behavior on large ranges, or you plan to work with fractional values, convert integers to double before computations, and convert back afterward if necessary.
Important points to remember:
Always use a dot for elementwise .*, ./, .\, and . ^ when both operands are arrays.
Addition and subtraction of arrays are always elementwise. There is no .+ or .- operator.
Combining a scalar with an array using +, -, *, /, or \ applies the scalar to every element of the array.
Most mathematical functions like sqrt, exp, and sin operate elementwise on arrays and return outputs of the same size.
Integer arithmetic can saturate at the minimum or maximum representable value if results go out of range.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Getting Started with MATLAB
- ☰ 1.1. What Is MATLAB and What Is It Used For
- ☰ 1.2. Installing MATLAB and Setting Up the Environment
- ☰ 1.3. Understanding the MATLAB Desktop Interface
- ☰ 1.4. Command Window, Workspace, and Current Folder
- ☰ 1.5. Basic Workflow and Running Simple Commands
- ☰ 1.6. Getting Help and Documentation
-
- ☰ 2. MATLAB Language Basics
- ☰ 2.1. MATLAB Syntax and Expressions
- ☰ 2.2. Variables and Assignment
- ☰ 2.3. Data Types and Type Conversion
- ☰ 2.4. Vectors and Matrices Fundamentals
- ☰ 2.5. Creating and Indexing Arrays
- ☰ 2.6. Basic Arithmetic and Elementwise Operations
- ☰ 2.7. Using Built-In Constants and Functions
-
- ☰ 3. Working with Variables and the Workspace
- ☰ 3.1. Creating, Viewing, and Editing Variables
- ☰ 3.2. Workspace Browser and Variable Inspector
- ☰ 3.3. Saving and Loading Data Files
- ☰ 3.4. MAT-Files and Importing External Data
- ☰ 3.5. Clearing Variables and Managing the Workspace
-
- ☰ 4. Vectors, Matrices, and Arrays
- ☰ 4.1. Row and Column Vectors
- ☰ 4.2. Matrix Creation and Concatenation
- ☰ 4.3. Indexing, Slicing, and Logical Indexing
- ☰ 4.4. Matrix Operations vs Elementwise Operations
- ☰ 4.5. Reshaping and Rearranging Arrays
- ☰ 4.6. Special Matrices and Functions
-
- ☰ 5. Basic Programming Constructs
- ☰ 5.1. Scripts vs Functions
- ☰ 5.2. Control Flow with if, elseif, else
- ☰ 5.3. Loops with for and while
- ☰ 5.4. break, continue, and return
- ☰ 5.5. Logical Expressions and Relational Operators
- ☰ 5.6. Best Practices for Clear and Readable Code
-
- ☰ 6. Functions in MATLAB
- ☰ 6.1. Creating Simple Functions
- ☰ 6.2. Function Inputs and Outputs
- ☰ 6.3. Function Files and the Path
- ☰ 6.4. Local vs Global Variables
- ☰ 6.5. Anonymous Functions
- ☰ 6.6. Organizing Code into Multiple Functions
-
- ☰ 7. Working with Numbers and Math
- ☰ 7.1. Scalars and Vectorized Computations
- ☰ 7.2. Basic Mathematical Functions
- ☰ 7.3. Trigonometric and Exponential Functions
- ☰ 7.4. Complex Numbers in MATLAB
- ☰ 7.5. Rounding, Modulo, and Special Values
- ☰ 7.6. Numerical Precision and Floating Point Considerations
-
- ☰ 8. Strings, Characters, and Categorical Data
- ☰ 8.1. Character Arrays and String Arrays
- ☰ 8.2. Creating and Manipulating Strings
- ☰ 8.3. Converting Between Data Types and Strings
- ☰ 8.4. Comparing and Searching Strings
- ☰ 8.5. Categorical Arrays Basics
-
- ☰ 9. Tables, Structures, and Cell Arrays
- ☰ 9.1. Introduction to Tables
- ☰ 9.2. Creating Tables and Accessing Data
- ☰ 9.3. Modifying and Joining Tables
- ☰ 9.4. Structures and Nested Structures
- ☰ 9.5. Cell Arrays and Cell Indexing
- ☰ 9.6. Choosing the Right Container Type
-
- ☰ 10. Importing and Exporting Data
- ☰ 10.1. Reading Text and CSV Files
- ☰ 10.2. Importing Excel Spreadsheets
- ☰ 10.3. Importing Data with the Import Tool
- ☰ 10.4. Exporting Data to Files
- ☰ 10.5. Working with Image and Audio Files
- ☰ 10.6. Basic File Management from MATLAB
-
- ☰ 11. Plotting and Visualization
- ☰ 11.1. Introduction to 2D Plotting
- ☰ 11.2. Customizing Plots and Axes
- ☰ 11.3. Multiple Plots in One Figure
- ☰ 11.4. Labels, Titles, Legends, and Annotations
- ☰ 11.5. Plotting with Different Line and Marker Styles
- ☰ 11.6. Saving and Exporting Figures
-
- ☰ 12. Advanced Plotting for Beginners
- ☰ 12.1. Subplots and Tiled Layouts
- ☰ 12.2. Bar, Scatter, and Stem Plots
- ☰ 12.3. Histograms and Density Plots
- ☰ 12.4. 3D Plots and Surface Plots
- ☰ 12.5. Using plottools and Interactive Editing
- ☰ 12.6. Basics of Handle Graphics
-
- ☰ 13. Working with Scripts and Live Scripts
- ☰ 13.1. Creating and Running Script Files
- ☰ 13.2. Sectioning Code and Running Sections
- ☰ 13.3. Live Scripts and Rich Text
- ☰ 13.4. Adding Equations, Images, and Outputs
- ☰ 13.5. Sharing and Exporting Live Scripts
-
- ☰ 14. Debugging and Code Quality
- ☰ 14.1. Finding and Fixing Syntax Errors
- ☰ 14.2. Setting Breakpoints and Stepping Through Code
- ☰ 14.3. Inspecting Variable Values During Execution
- ☰ 14.4. Using the Editor Debugging Tools
- ☰ 14.5. Using Code Analyzer and Warnings
- ☰ 14.6. Writing Clean and Maintainable MATLAB Code
-
- ☰ 15. Basic Linear Algebra with MATLAB
- ☰ 15.1. Vectors and Norms
- ☰ 15.2. Matrix Addition and Multiplication
- ☰ 15.3. Solving Linear Systems with Backslash
- ☰ 15.4. Inverses, Determinants, and Rank
- ☰ 15.5. Eigenvalues and Eigenvectors
- ☰ 15.6. Using Linear Algebra Functions Safely
-
- ☰ 16. Data Analysis and Statistics Fundamentals
- ☰ 16.1. Descriptive Statistics and Summary Measures
- ☰ 16.2. Sorting, Filtering, and Grouping Data
- ☰ 16.3. Basic Correlation and Regression
- ☰ 16.4. Simple Data Cleaning Techniques
- ☰ 16.5. Basic Time Series Handling
-
- ☰ 17. Working with Time and Dates
- ☰ 17.1. Representing Dates and Times
- ☰ 17.2. Creating and Formatting datetime Arrays
- ☰ 17.3. Date Calculations and Differences
- ☰ 17.4. Plotting Data over Time
-
- ☰ 18. Introduction to Signal and Image Handling
- ☰ 18.1. Basic Signal Representation in MATLAB
- ☰ 18.2. Simple Filtering and Transformations
- ☰ 18.3. Reading, Displaying, and Writing Images
- ☰ 18.4. Basic Image Transformations
-
- ☰ 19. Automation and Scripting Tasks
- ☰ 19.1. Batch Processing of Files
- ☰ 19.2. Writing Reusable Utility Scripts
- ☰ 19.3. Using Relative Paths and the MATLAB Path
- ☰ 19.4. Simple User Interaction with input and disp
-
- ☰ 20. Introduction to Toolboxes
- ☰ 20.1. What Are Toolboxes and How to Use Them
- ☰ 20.2. Exploring Installed Toolboxes
- ☰ 20.3. Finding Functions in Toolboxes
- ☰ 20.4. Add-Ons and MATLAB File Exchange
-
- ☰ 21. Best Practices and Next Steps
- ☰ 21.1. Organizing Projects and Folders
- ☰ 21.2. Version Control Basics with MATLAB
- ☰ 21.3. Performance Tips for Beginners
- ☰ 21.4. Learning Resources and Documentation Path
- ☰ 21.5. Suggested Practice Projects for Beginners
-
Comments
Please login to add a comment.
Don't have an account? Register now!