Matrices and Arrays
1/21/2025 Matrices and Arrays 1
Some useful commands
• clc; Clear command window. (home)
• clear; Clear variables and functions from memory.
• format; Set output format. Short (4 digits) Long (15 digits)
• Try : help disp;
1/21/2025 Matrices and Arrays 2
Creating variable at the command line
• Create a variable named 'a' by typing this statement at the command line
(>>):
• >> a= 1 ;
• When you do not specify an output variable, MATLAB uses the variable ans,
short for answer, to store the results of your calculation.
• >> sin(a)
• ans =
• 0.8415
1/21/2025 Matrices and Arrays 3
The Workspace window (on the right)
shows all the variables currently in the
workspace.
1/21/2025 Matrices and Arrays 4
Matrices and Arrays
• All MATLAB variables are multidimensional arrays, no matter what type
of data.
2D – Array 3D – Array
Array Creation : >> a = [1 2 3 4] ; creating a row vector
c = [3+4i, 4+3j; -i, 10j] ; Array with complex numbers
1/21/2025 Matrices and Arrays 5
Examples (Try it on MATLAB command window)
• Creating a matrix that has multiple rows, separate the rows with
semicolons.
• >> a = [1 3 5; 2 4 6; 7 8 10]
• Functions : ones, zeros, eye
• z = zeros(5,1) ; %create a 5-by-1 column vector of zeros.
• O=ones(1,5); %create a 1-by-5 row vector of ones.
1/21/2025 Matrices and Arrays 6
Matrix and Array Operations
• MATLAB allows you to process all the values in a matrix using a single
arithmetic operator or function.
• >> O = O+10;
• >> sin(a);
• To transpose (flip – interchanging rows and columns) a matrix, use a
single quote (‘):
• Matrix multiplication : a*a
1/21/2025 Matrices and Arrays 7
Dot operator (.)
• Given : >> a=[1 2 3;4 5 6; 7 8 9];
• Try : >> a.*a
• To perform element-wise multiplication rather than matrix multiplication,
use the .* operator.
• Try : >> a./3 ; AND >> a.^2;
1/21/2025 Matrices and Arrays 8
Concatenation (append or join)
• A=[a,a] ; concatenating ‘a’ with ‘a’ horizontally.
• C = horzcat(a,a);
• A=[a;a] ; concatenating ‘a’ with ‘a’ vertically.
• C = vertcat(a,a);
• The pair of square brackets [ ] is the concatenation operator.
1/21/2025 Matrices and Arrays 9
Saving and Loading Workspace Variables
• Save variables in your workspace to a MATLAB specific file format
called a MAT-file using the save command.
• To save the workspace to a MAT-file named filename.mat, use the
command:
• >> save filename
• >> load filename
• Saving the variable "k" to a new MAT-file called justk.mat:
• >> save justk k
1/21/2025 Matrices and Arrays 10
Using Built-in Functions and Constants
• >> a = pi (𝜋)
• https://in.mathworks.com/help/phased/ref/physconst.html
• >> a = sin(30)
• >> a =sin(pi/6)
• >> a = sqrt(16)
• You can perform calculations within the square brackets.
• x = [abs(-4) 4^2];
• y= [sqrt(10) pi^2]
1/21/2025 Matrices and Arrays 11
Creating Evenly-Spaced Vectors
• X = [ 1 2 3 4 ] – Vector contains evenly spaced number
• Shortcut method - X = 1:4 – “:” operator – start_value : end_value
• A = 1:2:10 - start_value : increment : end_value
• linspace(start_value , end_value, number_of_elements)
• If you wanted to create an evenly-spaced vector from 1 to 2π with
100 elements, would you use linspace or :?
1/21/2025 Matrices and Arrays 12
Array Creation Functions
• x = rand(2) - output will be a 2-by-2 matrix of random numbers.
• X = ones(1,3) or X = zeros (2,3)
• X = rand(size(X));
1/21/2025 Matrices and Arrays 13
Array Indexing – Single element
• Indexing is used to access selected elements of an array
• A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16];
• A(row,col)
• Single subscript traverses down each column in order – A(4,2) = A(8)
• What is the output for A(4,5)?
• You can specify elements outside the current dimensions.
• The size of the array increases to accommodate the newcomers.
1/21/2025 Matrices and Arrays 14
Array Indexing – Multiple elements
• To refer to multiple elements of an array, colon operator is used, which
allows you to specify a range of the form start : end.
• Try : A(1:3,2)
• Try : A(3,:)
• Try : A(2,2:end)
• Example : Extract the Third, Sixth, and Eight elements from A.
1/21/2025 Matrices and Arrays 15
Indexing Vectors
• A= [16 5 9 4 2 11 7 14];
• Swap the two halves of v to make a new vector:
• A2 = A([5:8 1:4])
• Extracting portions of an array: A(2:end-1)
• A(1:2:end) % Extract all the odd elements
• A(end:-1:1) % Reverse the order of elements
1/21/2025 Matrices and Arrays 16
Indexing Vectors
• A= [16 5 9 4 2 11 7 14];
• A([2 3 4]) = [10 15 20] % Replace some elements of A
• A([2 3]) = 30 % Replace second and third elements by 30
1/21/2025 Matrices and Arrays 17
Indexing Matrices with Two Subscripts
• A(row_x, col_y) - Extract the element in row_x, column_y
• A(row_n,:) – Extract nth row
• A(:,end) – Extract last column
• A(2:4,1:2)
1/21/2025 Matrices and Arrays 18
Linear Indexing
• When you index into the
matrix A using only one
subscript,
• MATLAB treats A as if its
elements were strung out in a
long column vector, by going
down the columns
consecutively.
• A(14) = A(2,4)
• A([6 12 15]) = 11 15 12
1/21/2025 Matrices and Arrays 19
Linear Indexing
• sub2ind that converts from row and
column subscripts to linear indices.
• idx = sub2ind(size(A), [2 3 4], [1 2 4])
• ans =
• 2 7 16
• A(idx)
• ans =
• 5 7 1
1/21/2025 Matrices and Arrays 20
Logical Indexing
• A(A > 12) extracts all the elements of A that are greater 12 into a logical
array (column vector).
• Many MATLAB functions that start with is return logical arrays and are
very useful for logical indexing.
• B(isnan(B)) = 0 - To replace all NaN elements of the matrix B with zero
• Strvalue(isspace(Strvalue)) = ‘_’ - replace all the spaces in a string
matrix Strvalue with underscores.
1/21/2025 Matrices and Arrays 21
Find function
• Logical indexing is closely related to the find function.
• FIND returns a vector containing the linear indices of each nonzero element
in array X.
• A(A > 5) is equivalent to A(find(A > 5))
• If X is a vector, then find returns a vector with the same orientation as X.
• If X is a multidimensional array, then find returns a column vector of the
linear indices of the result.
1/21/2025 Matrices and Arrays 22
Find function
•X=
• 16 2 3 13
• 5 11 10 8
• 9 7 6 12
• 4 14 15 1
• k = find(X<10,5) ; Find the first five elements that are less than 10
• X(k) ; View the corresponding elements of X.
• SEE - ind2sub - Convert linear indices to subscripts
1/21/2025 Matrices and Arrays 23
Changing Values in Arrays
• A(1,4)=0.5
• A(1,end)=0.2
1/21/2025 Matrices and Arrays 24
Performing Array Operations on Vectors
• Adding a scalar value to all the elements of an array.
• Add/Sub any two arrays of the same size.
• Multiply or divide all the elements of an array by a scalar.
• Basic statistical functions in MATLAB can be applied to a vector to produce a
single output. Max, Min, Sum, Sqrt
• .* operator performs elementwise multiplication and allows to multiply the
corresponding elements of two equally sized arrays.
• Ex : z = [3 4] .* [10 20] = ?
• Try : x = [1 2;3 4;5 6; 7 8].*[1;2;3;4]
1/21/2025 Matrices and Arrays 25
Compatible Array Sizes for Basic Operations
• Two inputs have compatible sizes if, for every dimension, the dimension
sizes of the inputs are either the same or one of them is 1.
• In the simplest cases, two array sizes are compatible if they are the
same or if one is a scalar.
Two inputs which are the same size One input is a scalar
Matrix and column vector with the same number of Column vector, Row vector
rows.
1/21/2025 Matrices and Arrays 26
Multidimensional Arrays
• Creating Multidimensional Arrays
• >> A = [1 2 3; 4 5 6; 7 8 9];
• Add a second page : A(:,:,2) = [10 11 12; 13 14 15; 16 17 18]
• B = cat(3,A,[3 2 1; 0 9 8; 5 3 7])
• The cat function can be a useful tool for building multidimensional
arrays.
• Expand a multidimensional array >> B(:,:,4) = 0
1/21/2025 Matrices and Arrays 27
Accessing Elements
• Try : C = A( : ,[1 3], :)
• Use the index vector [1 3] in the second dimension to access only the first and
last columns of each page of A.
• Try : D = A( 2:3, :, : )
• To find the second and third rows of each page, use the colon operator to create
your index vector.
1/21/2025 Matrices and Arrays 28
Manipulating Arrays - Reshape
B = reshape(A,[6 5])
Use the reshape function to rearrange
the elements of the 3-D array into a 6-
by-5 matrix.
B = 6×5
1 3 5 7 5
9 6 7 5 5
8 5 2 9 3
2 4 9 8 2
0 3 3 8 1
1 0 6 4 3
reshape operates columnwise, creating the new matrix by taking consecutive elements down each
column of A, starting with the first page then moving to the second page.
1/21/2025 Matrices and Arrays 29
Manipulating Arrays
• P1 = permute(M,[2 1 3]) - interchange row and column subscripts on
each page
• P2 = permute(M,[3 2 1]) - interchange row and page subscripts of M.
• M(:,:,1) = [1 2 3; 4 5 6; 7 8 9];
• M(:,:,2) = [0 5 4; 2 7 6; 9 3 1];
1/21/2025 Matrices and Arrays 30
Repeat copies of array
• Create a 3-by-2 matrix whose elements contain the value 10.
• >> A = repmat(10,3,2)
• A = 3×2
• 10 10
• 10 10
• 10 10
1/21/2025 Matrices and Arrays 31
Repeat copies of array
• Example :
• Try : A = diag([100 200 300]);
• Try : B = repmat(A,2,3);
• Example :
• Try : A = [1 2; 3 4];
• Try : B = repmat(A,[2 3 2]);
1/21/2025 Matrices and Arrays 32
Compatible Array Sizes for Basic Operations
• One input is a matrix, and the other is a 3-D array with the same
number of rows and columns.
1/21/2025 Matrices and Arrays 33
Compatible Array Sizes for Basic Operations
• One input is a matrix, and the other is a 3-D array. The dimensions are
all either the same or one of them is 1.
•
1/21/2025 Matrices and Arrays 34
Cell Array
• A cell array is a data type with indexed data containers called cells,
where each cell can contain any type of data.
• Cell arrays commonly contain either text, combinations of text and
numbers, or numeric arrays of different sizes.
• C = {'2017-08-16’, [56 67 78] }
• C(1,3) = {'Hello world’} - Adding new element
• C(2,:) = {'2017-08-17',[58 69 79],'dd’}; - Adding a new row.
1/21/2025 Matrices and Arrays 35
Table Array
• Table array with named variables that can contain different types.
• column-oriented data in variables
• LastName = {'Sanchez';'Johnson';'Li';'Diaz';'Brown'};
• Age = [38;43;38;40;49];
• Employed = logical([1;0;1;0;1]);
• Height = [71;69;64;67;64];
• Weight = [176;163;131;133;119];
• BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];
• T = table(LastName,Age,Employed,Height,Weight,BloodPressure);
1/21/2025 Matrices and Arrays 36
Table Array
• meanHeight = mean(T.Height); - Performing calculations
• T.BMI = (T.Weight*0.453592)./(T.Height*0.0254).^2 – Adding a new
column BMI
• T.Properties.Description = 'Patient data, including body mass index
(BMI) calculated using Height and Weight';
1/21/2025 Matrices and Arrays 37
Structure Array
• A structure array is a data type that groups related data using data containers
called fields.
• Each field can contain any type of data.
• Access data in a field using dot notation of the form structName.fieldName.
• Rectangle.L = 10;
• Rectangle.W = 5;
• Rectangle.Area = Rectangle.L * Rectangle.Area
• s = struct(obj) creates a scalar structure with field names and values that
correspond to properties of obj.
1/21/2025 Matrices and Arrays 38