Skip to main content
v2026.11,858 entries · CC-BY 4.0

Multiply Arrays in MATLAB: .* and times Guide

Learn how to multiply arrays in MATLAB element-wise using the .* operator, times function, and implicit expansion broadcasting with worked research examples.

Written and maintained by CASRAI Editorial Board

Last updated

To multiply arrays in MATLAB element-by-element, use the dot-star operator: C = A .* B or the equivalent functional form C = times(A, B). This executes array multiplication, computing the product of corresponding individual elements independently. In modern MATLAB (release R2016b and later), operands do not require identical dimensions as long as their shapes are compatible under implicit expansion (broadcasting). For linear algebraic matrix multiplication where inner matrix dimensions must match, use the standard asterisk operator * (matrix multiplication in MATLAB) or mtimes. This guide covers operator syntax, implicit expansion rules, multidimensional array scaling, and diagnostic error handling with verifiable research examples.

What it is used for in research

Element-wise array multiplication is essential across scientific computing, engineering, and data analysis. Unlike linear algebraic transformations that rotate, project, or map coordinate frames, array operations apply pointwise computations across structured datasets:

  • Signal and Audio Processing: Windowing time-domain sensor signals by multiplying raw data vectors element-by-element with tapering functions (such as Hann, Hamming, or Blackman windows) to suppress spectral leakage before computing Discrete Fourier Transforms.
  • Image Processing and Microscopy: Applying two-dimensional spatial intensity masks, Gaussian beam profiles, or binary segmentation regions of interest directly to experimental pixel matrices.
  • Data Normalization and Statistical Scaling: Weighting observations across multivariate feature matrices, scaling variables by reciprocal standard deviations, or applying sensor calibration gain curves across measurement channels.
  • Physical and Numerical Simulation: Evaluating localized physical laws over discrete spatial grids, such as computing instantaneous power dissipation P = V × I across paired voltage and current matrices, or calculating spatial kinetic energy densities.
  • High-Throughput Vectorized Computation: Eliminating inefficient element-by-element for loops in numerical routines by taking advantage of optimized, SIMD-accelerated array execution (MATLAB vectorize guide).

Install or access (official source only)

MATLAB is commercial technical computing software developed by The MathWorks, Inc. Researchers can access MATLAB through official MathWorks channels:

  • Institutional Campus-Wide Licenses: Academic and research institutions typically provide authorized desktop downloads and site-licensed activations via institutional MathWorks Accounts at the official MathWorks portal (mathworks.com).
  • MATLAB Online: Cloud-based execution accessible through standard modern web browsers via an authenticated MathWorks account, requiring no local desktop installation.
  • Base Platform Primitives: The array multiplication operator .* and its functional counterpart times are built-in core language primitives. They are included in base MATLAB without requiring specialized toolboxes and run across Linux, macOS, and Windows.
  • In-Product Documentation: Syntax summaries, argument definitions, and reference examples can be accessed directly from the MATLAB Command Window by executing doc times or help .*.

Step-by-step task

Follow these sequential steps to perform element-wise array multiplication in MATLAB.

  1. Define the arrays and check dimension compatibility: Verify that the arrays have matching sizes or compatible singleton dimensions. Check array shapes using the size function.

    A = [2, 4, 6; 8, 10, 12];
    B = [1, 3, 5; 2, 4, 6];
    size(A)
    size(B)

    Both arrays have dimension 2×3, so their dimensions match identically.

  2. Multiply arrays element-wise with the .* operator: Execute C = A .* B. Each resulting element C(i,j) is the product of A(i,j) and B(i,j).

    C = A .* B
    % Output:
    %      2    12    30
    %     16    40    72

    For example, position (1,1) is 2 × 1 = 2, and position (2,3) is 12 × 6 = 72.

  3. Execute functional multiplication using the times function: Call C = times(A, B) to produce the identical result.

    C_func = times(A, B);
    isequal(C, C_func)
    % ans = logical 1

    The functional form times is primarily used when passing multiplication as a function handle (such as @times) to higher-order functions like cellfun or when implementing custom object-oriented classes with operator overloading.

  4. Apply implicit expansion across differing array dimensions: Modern MATLAB automatically expands singleton dimensions (dimensions with size 1) to match the size of the corresponding dimension in the other operand.

    Example A: Scaling matrix rows with a column vector:

    M = [1, 2, 3; 4, 5, 6];      % 2x3 matrix
    v = [10; 100];               % 2x1 column vector
    scaledRows = M .* v
    % Output:
    %     10    20    30
    %    400   500   600

    Example B: Outer-product grid evaluation: Multiplying an M×1 column vector by a 1×N row vector expands both arrays into an M×N grid without manual duplication.

    x = [1; 2; 3];               % 3x1 column vector
    y = [10, 20, 30, 40];        % 1x4 row vector
    outerGrid = x .* y           % Result is 3x4
    % Output:
    %     10    20    30    40
    %     20    40    60    80
    %     30    60    90   120
  5. Multiply arrays by scalars and evaluate complex numbers:

    When multiplying an array by a scalar constant, A .* s and A * s yield identical outputs, scaling every entry in the array:

    scalarProduct = A .* 2.5;

    When multiplying complex arrays, .* multiplies complex numbers element-by-element without taking the complex conjugate:

    Z1 = [1 + 2i, 3 - 1i];
    Z2 = [2 + 1i, 1 + 2i];
    Z_out = Z1 .* Z2
    % Output:
    %    0 + 5i    5 + 5i

    For mathematical comparisons, see also exponentiation in MATLAB for .^ power rules and MATLAB square root for sqrt versus sqrtm.

Output and how to read it

Understanding the properties of the resulting array ensures correct downstream numerical processing:

  • Output Dimensionality: The dimensions of output array C equal the maximum dimension size across each axis: size(C, d) = max(size(A, d), size(B, d)). Use size(C) and ndims(C) to confirm array geometry before feeding results into subsequent analysis steps.
  • Numeric Classes and Type Promotion:
    • If both operands are double, the output is double.
    • If one operand is single and the other is double, MATLAB promotes the computation to single to preserve memory.
    • If multiplying an integer array (such as uint8 or int32) by a scalar double, the output retains the integer class and saturates at minimum or maximum integer bounds rather than wrapping around.
  • Logical Masks: Multiplying a numeric data matrix by a logical condition array (e.g., mask = A > 5) performs conditional filtering. Locations where the mask is false (0) evaluate to 0, while true (1) positions retain their original values.
  • Propagation of Special Values: IEEE 754 floating-point standards govern non-finite values:
    • NaN .* x yields NaN for any numerical value x.
    • 0 .* Inf yields NaN (indeterminate product).
    • Non-zero positive numbers multiplied by Inf yield Inf, while negative numbers yield -Inf.

    When generating synthetic matrices with randn MATLAB routines, ensure uninitialized or masked elements do not propagate unexpected NaN values into subsequent pipeline stages.

Troubleshooting

Address common syntax and sizing issues with these diagnostic solutions:

  • Error: “Arrays have incompatible sizes for this operation”:

    Cause: The dimension lengths of the two arrays do not match and neither dimension equals 1, preventing implicit expansion (for example, attempting to multiply a 2×3 array with a 2×4 array).

    Fix: Print dimensions using size(A) and size(B). Align matching dimensions or transpose one operand using the non-conjugate transpose operator .' (e.g., A .* B.') if one vector was oriented horizontally and the other vertically.

  • Accidental Linear Matrix Multiplication (* vs .*):

    Cause: Using * instead of .* on square matrices (such as two 3×3 matrices) will not produce a syntax error. Both operations execute successfully but compute completely different numerical results (linear algebra row-column dot products versus pointwise products).

    Fix: Verify whether your scientific formula requires an inner matrix product or a Hadamard pointwise product. Always use .* for element-by-element operations.

  • Legacy Code Compatibility (bsxfun vs Implicit Expansion):

    Cause: In code written before MATLAB R2016b, array broadcasting required bsxfun(@times, A, B).

    Fix: In modern MATLAB, replace bsxfun(@times, A, B) with A .* B. Modern implicit expansion is syntactically clearer and offers optimized memory access.

  • Integer Arithmetic Saturation:

    Cause: Multiplying integer types can truncate unexpectedly due to range saturation (e.g., uint8(200) .* uint8(2) saturates at 255 rather than 400).

    Fix: Cast integer data arrays to floating-point representation using double(A) .* double(B) before executing multiplication.

Free alternatives (table)

Element-wise array multiplication is supported across open-source computational environments with slight differences in operator conventions:

Environment Element-Wise Syntax Matrix Multiplication Syntax Dimension Broadcasting Official Sourced Reference
GNU Octave A .* B or times(A, B) A * B Automatic broadcasting identical to MATLAB GNU Octave Documentation: Arithmetic Operators
Python (NumPy) A * B or numpy.multiply(A, B) A @ B or numpy.matmul(A, B) NumPy array broadcasting NumPy Reference: numpy.multiply
Julia A .* B A * B Dot-syntax vectorized broadcasting Julia Manual: Mathematical Operations and Elementary Functions
R A * B A %*% B Vector recycling rule R Language Definition: Arithmetic Operators

Critical convention difference: In Python with NumPy, the plain asterisk * performs element-wise multiplication, whereas matrix multiplication requires the @ operator. In MATLAB, the convention is reversed: * is matrix multiplication, while .* is element-wise array multiplication.

FAQ

What is the difference between * and .* in MATLAB?

The .* operator performs element-by-element array multiplication, calculating the product of corresponding individual elements in arrays of compatible sizes. In contrast, the * operator performs linear algebraic matrix multiplication, where the number of columns in the first matrix must strictly equal the number of rows in the second matrix.

How do I multiply an array by a scalar in MATLAB?

You can use either C = A * scalar or C = A .* scalar. Both syntaxes produce identical numerical outputs because scalar multiplication scales every individual element across the entire array uniformly.

How does implicit expansion work in MATLAB array multiplication?

Introduced in MATLAB R2016b, implicit expansion allows binary element-wise operators like .* to operate on arrays of differing sizes as long as each dimension matches or is equal to 1. MATLAB automatically expands singleton dimensions across the corresponding dimension of the other array without requiring manual replication using repmat.

What is the difference between the times function and .* in MATLAB?

times(A, B) is the functional implementation of the .* operator. Both perform identical calculations. The functional form is used primarily when passing multiplication as a function handle (such as @times) to higher-order functions like cellfun or when overloading operators in custom object-oriented class definitions.

How can I multiply all elements within a single array in MATLAB?

To compute the total product of all elements within an array, use the built-in prod function. Calling P = prod(A, 'all') multiplies every element across all dimensions into a single scalar value. Calling prod(A, dim) computes products along a specific dimension.

Sources (official docs)

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Multiply Arrays in MATLAB: .* and times Guide

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →