7.1. Scalars and Vectorized Computations
Table of Contents
Understanding Scalars in MATLAB
In MATLAB a scalar is a single numeric value. It is the simplest kind of array and has size 1-by-1. When you type something like
a = 5;
b = 3.2;
both a and b are scalars. You can use scalars in all the usual arithmetic operations such as addition, subtraction, multiplication, division, and exponentiation. For example,
c = a + b; % scalar addition
d = a * b; % scalar multiplication
e = a^2; % scalar power
f = a / b; % scalar divisionBecause a scalar is treated as a 1-by-1 array, it also interacts naturally with vectors and matrices, which is fundamental for vectorized computations.
A scalar can be of different numeric types, such as double, single, or int32, but for most basic work MATLAB uses double precision by default. You can check the size and class of a scalar using size(a) and class(a) if you need to confirm that it is a simple 1-by-1 numeric value.
Scalars with Vectors and Matrices
One of the most common operations in MATLAB is combining scalars with vectors or matrices. MATLAB automatically applies a scalar operation to every element of the array. This is called scalar expansion.
If x is a vector and a is a scalar, then
y = x + a;
adds a to every element of x. For example,
x = [1 2 3];
a = 10;
y = x + a; % result is [11 12 13]
The same idea works for subtraction, multiplication, and division. A scalar can multiply an array element by element using standard * applied as scalar times array,
A = [1 2; 3 4];
k = 2;
B = k * A; % every element doubled, [2 4; 6 8]and similarly
C = A + 5; % adds 5 to every element of A
D = A / 2; % divides every element of A by 2When you write a scalar on the left or on the right, MATLAB interprets it as an elementwise operation repeated across the entire array. This is different from matrix multiplication between two arrays, which must follow matrix dimension rules and is covered elsewhere. With one scalar involved MATLAB does not need to check matrix dimension compatibility.
What Vectorized Computations Mean
Vectorized computation means you write MATLAB expressions that operate on whole vectors or matrices at once, instead of writing your own explicit loops that work element by element. MATLAB is designed around this idea.
For example, suppose you want to compute the square of every element of a vector. A loop based approach could look like this:
x = 1:5;
for i = 1:length(x)
y(i) = x(i)^2;
endA vectorized approach uses array operations directly:
x = 1:5;
y = x.^2;
The second version lets MATLAB perform the computation on the entire array x in one step. It is usually shorter, easier to read, and often faster. The key to vectorized computations is that you think in terms of whole arrays, and you use MATLAB operations that already know how to work on arrays without writing explicit for or while loops for each element.
Vectorization appears whenever you use basic arithmetic operators with arrays, and whenever you call built-in functions that accept vectors or matrices and return array results in a single call.
Elementwise Operations for Vectorization
A central tool for vectorized computations is elementwise operators. Some operators in MATLAB have two related forms. One form is for matrix algebra, and another form is for element by element work.
For elementwise multiplication, division, and powers you use a dot in front of the operator:
.*for elementwise multiplication./for elementwise right division.\for elementwise left division.^for elementwise power
Even though + and - are already elementwise when applied to arrays of the same size, *, /, and ^ without a dot are not elementwise between arrays. They follow matrix algebra rules. The dot version of these operators lets you apply the operation separately to each position in the arrays.
For example, if you have two vectors of the same size,
x = [1 2 3];
y = [4 5 6];
z = x .* y; % result [4 10 18]
each element of x is multiplied with the corresponding element of y. Similarly, elementwise power lets you do things like
x = 1:4;
p = x.^3; % cubes each element, [1 8 27 64]which is a typical vectorized expression.
Vectorized Computations with Functions
Most mathematical functions in MATLAB are written to accept vectors and matrices directly. When you call such a function with an array input, it usually applies the function to each element independently. This behavior makes it easy to write vectorized code.
If x is a vector of angles in radians,
x = [0 pi/4 pi/2];
y = sin(x);
then y is a vector where each entry is the sine of the corresponding entry of x. There is no need to loop over x yourself. Many functions work this way, such as cos, exp, log, sqrt, and others that you will see in this part of the course.
You can also combine elementwise operators with such functions to build more complicated vectorized expressions. For example, to compute
$$
f(x) = e^{-x} \sin(x)
$$
for many values of x in a single step, you can write
x = linspace(0, 2*pi, 100);
f = exp(-x) .* sin(x);
Here exp(-x) returns a vector, sin(x) returns a vector, and .* multiplies them element by element. There is no loop, but you still get every function value over the whole range of x in one expression.
Using Scalars to Build Vectorized Expressions
Scalars combine naturally with vectorization, because they can shift, scale, or bias an entire array in one statement. This makes scalar operations useful when you want to transform vectors or matrices as part of a larger computation.
For example, adding a scalar can shift an entire signal up or down:
t = 0:0.01:1;
x = sin(2*pi*5*t); % a sine wave
x_shifted = x + 0.5; % raise all values by 0.5Multiplying by a scalar can scale an entire dataset:
data = rand(1, 100); % random numbers between 0 and 1
scaled = 10 * data; % random numbers between 0 and 10You can combine several scalar operations and elementwise operations in one vectorized expression. For example, if you want to compute a simple quadratic expression
$$
y = a x^2 + b x + c
$$
for many x values at once, you can write
a = 2;
b = -3;
c = 1;
x = -5:0.1:5;
y = a*x.^2 + b*x + c;
In this expression, the scalar coefficients a, b, and c affect every element of x without any explicit loops.
Performance and Clarity Benefits of Vectorization
Vectorized computations often run faster than equivalent loops in MATLAB, especially for medium and large arrays. MATLAB is implemented in a way that can take advantage of highly optimized library routines when you operate on whole arrays. If you write elementwise loops in MATLAB code, you usually add interpretation overhead that slows things down compared to the built-in array behavior.
Vectorized code is also usually shorter and clearer. Instead of several lines that set up loops, index variables, and assignments, a vectorized statement can show the mathematical idea directly. For example,
for i = 1:length(x)
y(i) = 2*x(i) + 5;
endcan be replaced with
y = 2*x + 5;In many cases the shorter version is easier to read and has fewer places for indexing errors or off-by-one mistakes. Even though you should still understand how loops work, vectorized style fits MATLAB particularly well.
Recognizing When Vectorization Is Possible
Not every algorithm can be completely vectorized, but many beginner tasks can. It helps to learn to recognize when you can rewrite a loop in terms of array operations.
In simple terms, if each output element depends only on the corresponding positions in one or more input arrays, and not on previous outputs or a changing internal state, then you likely can express the whole computation with elementwise operations or functions that operate on arrays. For instance, transforming every element with the same formula, scaling and shifting arrays, or combining arrays entry by entry are all scenarios that work well with vectorized expressions.
On the other hand, if your code needs information that depends on earlier steps in a sequence, such as cumulative decisions or updates that change with each iteration, complete vectorization might not be straightforward. In such cases, you can still benefit from vectorized pieces inside a larger loop, but the entire algorithm may not become one short vectorized expression.
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!