Kahibaro
Discord Login Register

7.1 Scalars and Vectorized Computations

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

matlab
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,

matlab
c = a + b;     % scalar addition
d = a * b;     % scalar multiplication
e = a^2;       % scalar power
f = a / b;     % scalar division

Because 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

matlab
y = x + a;

adds a to every element of x. For example,

matlab
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,

matlab
A = [1 2; 3 4];
k = 2;
B = k * A;     % every element doubled, [2 4; 6 8]

and similarly

matlab
C = A + 5;     % adds 5 to every element of A
D = A / 2;     % divides every element of A by 2

When 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:

matlab
x = 1:5;
for i = 1:length(x)
    y(i) = x(i)^2;
end

A vectorized approach uses array operations directly:

matlab
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:

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,

matlab
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

matlab
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,

matlab
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

matlab
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:

matlab
t = 0:0.01:1;
x = sin(2*pi*5*t);        % a sine wave
x_shifted = x + 0.5;      % raise all values by 0.5

Multiplying by a scalar can scale an entire dataset:

matlab
data = rand(1, 100);      % random numbers between 0 and 1
scaled = 10 * data;       % random numbers between 0 and 10

You 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

matlab
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,

matlab
for i = 1:length(x)
    y(i) = 2*x(i) + 5;
end

can be replaced with

matlab
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: 64

Comments

Please login to add a comment.

Don't have an account? Register now!