Kahibaro
Discord Login Register

Creating and Indexing Arrays

Introduction

In MATLAB, almost everything you do involves arrays. Scalars, vectors, matrices, and even many types of data collections are all treated as arrays in different shapes. This chapter focuses on how to create arrays in different ways and how to access their elements using indexing. You will use these skills constantly, so it is worth getting comfortable with the notation and behavior.

Creating Arrays with Brackets

The most direct way to create numeric arrays is to write their elements inside square brackets. MATLAB uses spaces or commas to separate columns, and semicolons to separate rows.

To create a row vector, place the elements in brackets, separated by spaces or commas:

matlab
v = [1 2 3 4]
w = [10, 20, 30]

Here v has size 1 x 4, and w has size 1 x 3. The output is shown as a row.

To create a column vector, use semicolons between elements:

matlab
c = [1; 2; 3; 4]

Now c has size 4 x 1. The semicolon tells MATLAB to go to a new row.

To create a general matrix, combine spaces (or commas) and semicolons:

matlab
A = [1 2 3; 4 5 6]

Here A is a 2 x 3 matrix. The first row is [1 2 3], the second row is [4 5 6].

All rows in a 2D numeric array must have the same number of elements. If they do not, MATLAB gives an error when you try to create the array.

You are not limited to literal numbers. Any expression that evaluates to a scalar can be used inside the brackets:

matlab
x = 10;
B = [x 2*x x^2]

After evaluation, B becomes [10 20 100].

Creating Arrays with the Colon Operator

MATLAB has a special shorthand to create regularly spaced vectors using the colon operator :. The simplest form is:

matlab
a = 1:5

This creates the row vector [1 2 3 4 5]. The default step size is 1. The general pattern is

$$\text{start}:\text{step}:\text{end}$$

For example:

matlab
b = 0:2:10    % 0, 2, 4, 6, 8, 10
c = 5:-1:1    % 5, 4, 3, 2, 1

If the step is positive, the sequence increases until it reaches or passes the end value. If the step is negative, the sequence decreases until it reaches or passes the end. The end value is included only if it lands exactly on one of the step increments.

For example:

matlab
d = 0:3:10    % gives [0 3 6 9], not 12

The value 12 is beyond 10, so it is not included.

The colon operator always creates a row vector. You can transpose it to get a column vector using the transpose operator:

matlab
r = (1:4)'    % column vector [1; 2; 3; 4]

Later, you will see other functions that create linearly or nonlinearly spaced arrays, but the colon operator is the standard tool for simple ranges of integers or evenly spaced numbers.

Using Functions to Create Arrays

In addition to brackets and the colon operator, MATLAB provides simple functions to create common arrays quickly.

The function zeros creates an array of all zeros. You pass the desired size as arguments. For a matrix with m rows and n columns, use:

matlab
Z = zeros(3, 4)

This gives a 3 x 4 matrix with every element equal to 0. For a vector, you can specify one dimension as 1:

matlab
zrow = zeros(1, 5)   % 1 x 5 row vector
zcol = zeros(5, 1)   % 5 x 1 column vector

The function ones works the same way but fills the array with 1s:

matlab
O = ones(2, 3)

To create an array of a specific constant value, you can multiply ones by that value:

matlab
C = 7 * ones(2, 2)   % all elements equal to 7

The function eye creates an identity matrix, which is a square matrix with ones on the main diagonal and zeros elsewhere:

matlab
I = eye(3)    % 3 x 3 identity matrix

For now, you mainly need to know that zeros, ones, and eye are convenient ways to create arrays of a given size without manually listing every element.

Combining Arrays by Concatenation

You can build larger arrays by joining smaller arrays together. This is called concatenation. In MATLAB you again use square brackets, with spaces or commas for horizontal concatenation and semicolons for vertical concatenation.

Horizontal concatenation puts arrays side by side to form more columns, as long as they have the same number of rows:

matlab
A = [1 2; 3 4];   % 2 x 2
B = [5 6; 7 8];   % 2 x 2
H = [A B]         % 2 x 4

Here the result H has the first two columns from A and the next two columns from B. You can also insert a scalar or vector in the same way if the dimensions are compatible:

matlab
v = [9; 10];      % 2 x 1 column vector
H2 = [A v]        % 2 x 3

Vertical concatenation stacks arrays on top of each other to form more rows, as long as they have the same number of columns:

matlab
V = [A; B]        % 4 x 2

Since A and B are both 2 x 2, stacking them produces a 4 x 2 matrix. Again, scalars and vectors can be stacked if their sizes match the columns:

matlab
row = [11 12];    % 1 x 2 row vector
V2 = [row; A]     % 3 x 2

When concatenating, the dimensions must match in the nonconcatenating direction. If they do not, MATLAB gives an error. This also means that a row vector and a column vector cannot be concatenated directly side by side without reshaping one of them.

Basic Indexing with Parentheses

Once you have an array, you usually want to access or modify individual elements or groups of elements. MATLAB uses parentheses () for indexing. For 2D arrays you provide row and column indices:

matlab
A = [10 20 30; 40 50 60; 70 80 90];
x = A(2, 3)    % element in row 2, column 3

In this example x becomes 60. The general form for a 2D array is A(row, column). Indexing in MATLAB starts at 1, not at 0. The first element of a row vector v is v(1), and so on.

Index values must be positive integers within the size of the array. If you try to access A(4,1) when A has only 3 rows, MATLAB throws an error.

You can also assign new values to elements using indexing:

matlab
A(1, 2) = 25;     % change row 1, column 2 to 25
A(3, 1) = 0;      % change row 3, column 1 to 0

After these assignments, the content of A is updated accordingly.

Indexing with Colon to Select Whole Rows or Columns

The colon operator is also used inside indexing expressions to select all elements along a dimension. In a 2D array, : means "all rows" or "all columns", depending on the position.

For example, to select a whole row:

matlab
row2 = A(2, :)    % all columns in row 2

Here row2 is a row vector containing the entire second row of A.

To select a whole column:

matlab
col3 = A(:, 3)    % all rows in column 3

This gives a column vector with all elements from the third column of A.

You can also assign to entire rows or columns at once:

matlab
A(1, :) = [1 2 3];   % replace entire first row
A(:, 2) = 0;         % set entire second column to 0

In these assignments, the right side must have a size compatible with the part you are replacing.

Indexing with Ranges and Steps

You can combine the colon operator with numeric limits to select a range of rows or columns. Inside indexing parentheses, start:end creates a set of consecutive indices, and you can also provide a step if needed.

To select certain columns:

matlab
sub = A(:, 1:2)      % all rows, columns 1 to 2

Now sub contains the first two columns of A. To select certain rows:

matlab
rows13 = A(1:3, :)   % rows 1 to 3, all columns

To skip rows or columns using a step, use the start:step:end form:

matlab
oddRows = A(1:2:end, :)   % every second row starting at 1

If you have a vector, you can select its elements in the same way:

matlab
v = 10:10:100;      % [10 20 30 40 50 60 70 80 90 100]
part = v(3:6);      % [30 40 50 60]
stepPart = v(1:2:end);   % [10 30 50 70 90]

These indexing expressions do not change the original array. They create new arrays that contain copies of the selected elements.

Linear Indexing

MATLAB also allows you to index an array using a single subscript. This is called linear indexing. In linear indexing, MATLAB treats the array as if its columns are stacked on top of each other into one long column vector.

For a matrix A, A(k) refers to the k th element in column major order. The counting goes down the first column, then down the second column, and so on. For example:

matlab
A = [ 1  4  7;
      2  5  8;
      3  6  9 ];
e1 = A(1)    % 1
e2 = A(2)    % 2
e3 = A(3)    % 3
e4 = A(4)    % 4

Here A(4) refers to the first element of the second column. In general, if A has m rows, then element A(i, j) corresponds to linear index

$$k = i + (j - 1) \cdot m.$$

Although you do not need to memorize this formula initially, it helps to understand how single indices map to row and column positions. Linear indexing is especially useful when you operate on all elements in an array or when you work with functions that naturally produce a vector of linear indices.

You can also use linear indexing to assign values:

matlab
A(5) = 100;  % change the 5th element in column-major order

This assigns the value to A(2, 2) in this example, since that is the fifth element in the column-wise sequence.

Using the end Keyword in Indexing

Within an indexing expression, MATLAB provides the special keyword end. It represents the largest valid index for that dimension of the array.

For a vector v, v(end) is the last element:

matlab
v = [10 20 30 40];
last = v(end);          % 40
secondLast = v(end-1);  % 30

For a 2D array, you can use end separately for rows and columns:

matlab
A = [1 2 3; 4 5 6; 7 8 9];
bottomRight = A(end, end);     % 9
lastRow = A(end, :);           % [7 8 9]
lastTwoCols = A(:, end-1:end); % columns 2 and 3

This syntax is very convenient when you do not know the exact size of the array in advance or when you want to write code that works for different sized inputs.

Expanding Arrays by Indexing

In some situations, you might assign to an index that is beyond the current size of the array. MATLAB then automatically enlarges the array so that the new index is valid. Any new elements that are created in the process are filled with zero.

For example:

matlab
v = [1 2 3];
v(5) = 10;

After this, v becomes [1 2 3 0 10]. The missing element at position 4 is automatically set to 0.

The same behavior occurs for matrices:

matlab
A = [1 2; 3 4];
A(3, 3) = 9;

The array A grows to a 3 x 3 matrix. The new elements at positions (1,3), (2,3), and (3,1:2) are set to 0, and (3,3) is set to 9.

While this automatic expansion is convenient, creating arrays by gradual growth in a loop can be inefficient for performance. There are better approaches for that, which you will encounter later. For now, it is important to know that MATLAB does allow you to grow arrays through indexed assignment and that missing elements become zeros.

Summary

In this chapter you have seen several key ways to create arrays, including brackets, the colon operator, and basic array creation functions. You have also learned the core indexing features that let you access and modify individual elements, rows, columns, and subarrays.

Views: 4

Comments

Please login to add a comment.

Don't have an account? Register now!