Skip to content

MATLAB - Array Functions

MATLAB is a matrix-based language, meaning arrays (vectors and matrices) are first-class citizens. Efficiently creating and manipulating arrays is the most critical skill for any MATLAB user. This tutorial covers the fundamental functions for array creation, inspection, and manipulation.

These functions are used to initialize arrays of a specific size and content.

Function NameDescription
zerosCreates an array of all zeros.
onesCreates an array of all ones.
eyeCreates an identity matrix (ones on the diagonal, zeros elsewhere).
randCreates an array of uniformly distributed random numbers between 0 and 1.
randnCreates an array of normally distributed (Gaussian) random numbers with mean 0 and variance 1.
linspaceCreates a vector of linearly spaced points between two endpoints.
magicCreates a magic square matrix (for demonstration purposes).
% Create a 3x4 matrix of zeros
A = zeros(3, 4);
% Create a 2x2 matrix of ones
B = ones(2, 2);
% Create a 4x4 identity matrix
I = eye(4);
% --- Reproducible Random Numbers ---
% Best Practice: Set the random seed for reproducible results
rng('default');
% Create a 2x5 matrix of uniformly distributed random numbers
U = rand(2, 5);
% Create a 3x1 column vector of normally distributed random numbers
N = randn(3, 1);

Once an array exists, you need to query its properties and change its shape.

Function NameDescription
sizeReturns the dimensions of the array as a row vector.
lengthReturns the length of the largest dimension.
numelReturns the total number of elements in the array.
reshapeChanges the dimensions of an array without changing its data.
' (apostrophe)Performs the complex conjugate transpose. For real matrices, this is the simple transpose.
transposePerforms the non-conjugate transpose.
% Create a sample matrix
M = [1, 2, 3; 4, 5, 6];
% Get size information
dims = size(M) % Result: [2, 3]
num_elements = numel(M) % Result: 6
% Reshape the 2x3 matrix into a 3x2 matrix
M_reshaped = reshape(M, 3, 2);
% Result:
% 1 5
% 4 3
% 2 6
% Transpose the matrix
M_transposed = M'; % Use the apostrophe operator for transpose
% Result:
% 1 4
% 2 5
% 3 6

III. Mathematical and Statistical Functions

Section titled “III. Mathematical and Statistical Functions”

MATLAB provides a rich library of functions that operate on entire arrays at once, a concept known as vectorization.

Function NameDescription & Key Usage
sumsum(A) sums each column. sum(A, 2) sums each row. sum(A, 'all') sums all elements.
meanmean(A) finds the mean of each column. Use dimensions like sum for other cases.
maxmax(A) finds the maximum of each column. [M, I] = max(A) also returns the index.
minFinds the minimum element, similar syntax to max.
sortsort(A) sorts each column. sort(A, 'descend') sorts in descending order.
uniqueReturns the unique elements of an array, sorted.
% Let's analyze a matrix of grades for 3 students across 4 tests
grades = [85, 92, 78, 88; ...
95, 89, 91, 94; ...
76, 81, 85, 79];
% Calculate the average grade for each test (mean of each column)
avg_test_grade = mean(grades)
% Result: [85.33, 87.33, 84.67, 87.00]
% Calculate the average grade for each student (mean of each row)
avg_student_grade = mean(grades, 2)
% Result:
% 85.75
% 92.25
% 80.25
% Find the highest grade on each test (max of each column)
[highest_grades, student_id] = max(grades)
% Result:
% highest_grades = [95, 92, 91, 94]
% student_id = [2, 1, 2, 2] (Student 2 got the highest on 3 tests)
% Find the total score for all tests combined
total_score = sum(grades, 'all')
% Result: 1018

A core principle of effective MATLAB programming is vectorization. This means using array-wide operations instead of for loops whenever possible. Vectorized code is more concise, readable, and significantly faster.

% --- The Slow, Non-Vectorized Way (AVOID) ---
x = 1:1000;
y = zeros(size(x));
for i = 1:length(x)
y(i) = sin(x(i));
end
% --- The Fast, Vectorized MATLAB Way (PREFER) ---
x = 1:1000;
y = sin(x); % Apply sin directly to the entire vector