MATLAB Vectorization

MATLAB Vectorization lets you express repeated calculations as operations on entire arrays. You use it when many samples follow the same mathematical rule, such as converting sensor readings or calculating power for several operating conditions. The central task is to preserve what each sample means while replacing individual calculations with array expressions.

Express the sample rule as an array operation

Vectorization means expressing a calculation through array operations rather than explicitly processing each element in a loop. Start by writing the rule for one sample. For electrical measurements,


Pi=Vi2Ri,P_i = \frac{V_i^2}{R_i},


where ViV_i is voltage in volts, RiR_i is resistance in ohms, and PiP_i is power in watts. If V and R have matching sizes and corresponding sample positions, write:


MATLAB
P = V.^2 ./ R;


The operator .^ squares each voltage, and ./ divides each squared voltage by its corresponding resistance. Use .* when multiplying corresponding array elements. Addition and subtraction already operate element by element, so they need no dot.


For example, x = [2 4 6]; y = x.^2 + 3; produces y = [7 19 39]. The scalar 3 is added to every squared element. Functions such as sin, sqrt, and exp also accept array inputs and evaluate their elements.



Select readings with a logical mask

A logical mask is an array of true and false values identifying positions that satisfy a condition. MATLAB commonly displays these logical values as 1 and 0. A comparison such as keep = x >= lower; tests every element.


To retain a closed interval, combine two comparisons:


MATLAB
keep = (x >= lower) & (x <= upper);
xAccepted = x(keep);


Here, & requires both conditions at each position. Logical indexing returns the accepted values in their original order. If another vector contains measurements from the same samples, apply the same mask to that vector to preserve correspondence.


Four connected boxes show readings being tested, selected with a logical mask, and processed together.


Selection, replacement, and counting serve different purposes:


Expression

Purpose

Effect for a row vector

x(keep)

Select accepted values

Returns only accepted entries

x.*keep

Multiply by logical values

Keeps all positions; finite rejected values become zero

sum(keep)

Count accepted values

Returns one count

mean(x(keep))

Average accepted values

Uses only accepted entries


For a meaningful accepted-sample average, check that the mask selects at least one reading. Averaging zero-filled rejected positions instead changes the denominator and therefore changes the quantity you calculate.



Check shapes as well as values

For paired samples, matching lengths are insufficient: orientation matters. A row vector has size 1×n1\times n, while a column vector has size n×1n\times1. Modern MATLAB can implicitly expand these into an n×nn\times n result during element-wise arithmetic. That result combines different sample positions instead of performing the intended pairwise calculation.


Use size to inspect inputs and outputs. When two vectors represent the same ordered samples, a = a(:); b = b(:); makes both column vectors before you combine them. This standardizes orientation but does not verify sample order or equal lengths.


Vectorization can improve clarity and speed, but large intermediate arrays can increase memory use. Check the numerical meaning and output size first; measure performance when speed matters.

What to remember

  • Translate the single-sample rule into appropriate array operations.
  • Build logical masks from explicit validity conditions.
  • Select entries before restricted arithmetic or accepted-sample summaries.
  • Check array shapes and sample correspondence before combining vectors.

Example: Filter a displacement calibration

A displacement sensor records voltages u = [0.5 1.0 1.5 2.0 3.0 3.5] in volts. Its supplied calibration is


x=ku2,k=0.0200 m/V2.x=ku^2,\qquad k=0.0200\ \text{m/V}^2.


The calibration is valid only from 1.0 V through 3.0 V, including both endpoints. Treat the accepted readings as equally weighted samples and retain full precision until the final result.


a) Write vectorized code to identify the valid readings and extract their voltages. State the mask and accepted voltage vector.


Test every voltage against both inclusive bounds. A reading is accepted only when both comparisons are true, so combine them with element-wise AND:


MATLAB
keep = (u >= 1.0) & (u <= 3.0);
uAccepted = u(keep);


The lower-bound comparison gives logical [0 1 1 1 1 1], while the upper-bound comparison gives logical [1 1 1 1 1 0]. Their intersection is logical [0 1 1 1 1 0].


Thus, uAccepted = [1.0 1.5 2.0 3.0] V. There are ________ accepted readings, and both calibration endpoints are retained.


b) Calculate the displacement corresponding to each accepted voltage using one vectorized expression.


Square each accepted voltage independently with .^, then multiply by the supplied scalar calibration coefficient. Selection occurs before the calibration is applied, so the reported displacement vector contains only valid calibrated readings.


MATLAB
k = 0.0200;
xAccepted = k .* uAccepted.^2;


The individual calculations are:


x1=(0.0200 m/V2)(1.0 V)2=0.0200 m,x2=(0.0200 m/V2)(1.5 V)2=0.0450 m,x3=(0.0200 m/V2)(2.0 V)2=0.0800 m,x4=(0.0200 m/V2)(3.0 V)2=0.1800 m.\begin{aligned} x_1&=(0.0200\ \text{m/V}^2)(1.0\ \text{V})^2=0.0200\ \text{m},\\ x_2&=(0.0200\ \text{m/V}^2)(1.5\ \text{V})^2=0.0450\ \text{m},\\ x_3&=(0.0200\ \text{m/V}^2)(2.0\ \text{V})^2=0.0800\ \text{m},\\ x_4&=(0.0200\ \text{m/V}^2)(3.0\ \text{V})^2=0.1800\ \text{m}. \end{aligned}


The voltage-squared units cancel those in the coefficient. The result is xAccepted = [0.0200 0.0450 0.0800 0.1800] m, in the same order as the accepted voltages.


c) Calculate the arithmetic mean accepted displacement in metres, to five decimal places.


Average the ________ calibrated displacements. The rejected readings contribute neither a displacement nor a place in the denominator. You can calculate the result directly from the selected vector:


MATLAB
meanDisplacement = mean(xAccepted);


First sum the accepted values:


∑xi=0.0200+0.0450+0.0800+0.1800=0.3250 m.\sum x_i=0.0200+0.0450+0.0800+0.1800=0.3250\ \text{m}.


Then divide by the number of accepted readings:


x‾=0.3250 m4=0.08125 m.\overline{x}=\frac{0.3250\ \text{m}}{4}=0.08125\ \text{m}.


The mean accepted displacement is 0.08125 m0.08125\ \text{m} to five decimal places. It lies between the smallest and largest accepted displacements, providing a useful numerical check. Calibrating an average voltage instead would calculate a different quantity because the calibration contains a square.

Three electrical operating conditions have voltages V = [4 6 8] in volts and resistances R = [2 3 4] in ohms. Corresponding entries belong to the same condition. Which MATLAB expression calculates the power of each condition in watts using Pi=Vi2/RiP_i=V_i^2/R_i?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A motor controller stores a nonempty row vector I of finite current readings in amperes. It needs two scalar logical results: whether at least one reading exceeds 12 A, and whether every reading is at most 12 A.


Complete the instructions with MATLAB function names. Do not enter operators or complete expressions.


For the first result, apply to I > 12. For the second result, apply to I <= 12.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A thermal test records times t = [0 2 4 6 8] in seconds and corresponding temperatures T = [295 305 315 325 335] in kelvin. Which expression returns the times at which the temperature is from 305 K through 325 K, including both endpoints?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice