MATLAB - Array Functions
MATLAB - Essential Array Functions
Section titled “MATLAB - Essential 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.
I. Array Creation Functions
Section titled “I. Array Creation Functions”These functions are used to initialize arrays of a specific size and content.
| Function Name | Description |
|---|---|
zeros | Creates an array of all zeros. |
ones | Creates an array of all ones. |
eye | Creates an identity matrix (ones on the diagonal, zeros elsewhere). |
rand | Creates an array of uniformly distributed random numbers between 0 and 1. |
randn | Creates an array of normally distributed (Gaussian) random numbers with mean 0 and variance 1. |
linspace | Creates a vector of linearly spaced points between two endpoints. |
magic | Creates a magic square matrix (for demonstration purposes). |
Example: Creating Various Arrays
Section titled “Example: Creating Various Arrays”% Create a 3x4 matrix of zerosA = zeros(3, 4);
% Create a 2x2 matrix of onesB = ones(2, 2);
% Create a 4x4 identity matrixI = eye(4);
% --- Reproducible Random Numbers ---% Best Practice: Set the random seed for reproducible resultsrng('default');
% Create a 2x5 matrix of uniformly distributed random numbersU = rand(2, 5);
% Create a 3x1 column vector of normally distributed random numbersN = randn(3, 1);II. Array Information & Manipulation
Section titled “II. Array Information & Manipulation”Once an array exists, you need to query its properties and change its shape.
| Function Name | Description |
|---|---|
size | Returns the dimensions of the array as a row vector. |
length | Returns the length of the largest dimension. |
numel | Returns the total number of elements in the array. |
reshape | Changes the dimensions of an array without changing its data. |
' (apostrophe) | Performs the complex conjugate transpose. For real matrices, this is the simple transpose. |
transpose | Performs the non-conjugate transpose. |
Example: Inspecting and Reshaping
Section titled “Example: Inspecting and Reshaping”% Create a sample matrixM = [1, 2, 3; 4, 5, 6];
% Get size informationdims = size(M) % Result: [2, 3]num_elements = numel(M) % Result: 6
% Reshape the 2x3 matrix into a 3x2 matrixM_reshaped = reshape(M, 3, 2);% Result:% 1 5% 4 3% 2 6
% Transpose the matrixM_transposed = M'; % Use the apostrophe operator for transpose% Result:% 1 4% 2 5% 3 6III. 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 Name | Description & Key Usage |
|---|---|
sum | sum(A) sums each column. sum(A, 2) sums each row. sum(A, 'all') sums all elements. |
mean | mean(A) finds the mean of each column. Use dimensions like sum for other cases. |
max | max(A) finds the maximum of each column. [M, I] = max(A) also returns the index. |
min | Finds the minimum element, similar syntax to max. |
sort | sort(A) sorts each column. sort(A, 'descend') sorts in descending order. |
unique | Returns the unique elements of an array, sorted. |
Example: Data Analysis on a Matrix
Section titled “Example: Data Analysis on a Matrix”% Let's analyze a matrix of grades for 3 students across 4 testsgrades = [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 combinedtotal_score = sum(grades, 'all')% Result: 1018Best Practice: Vectorization
Section titled “Best Practice: Vectorization”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