Lecture 3

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 10

IT Workshop

Programming in MATLAB
Lecture-3: Array Indexing
Array Indexing

When you want to access selected elements of an


array, use indexing.
For example, consider the 4-by-4 magic square A:
A = magic(4)
A=

16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
Array Indexing- Indexing by Position

There are three primary approaches to accessing array elements


based on their location (index) in the array. These approaches
are indexing by position, linear indexing, and logical indexing.
The most common way is to specify row and column subscripts,
such as:
Row
Column
A=
A(4,2) 16 2 3 13
ans = 14 5 11 10 8
9 7 6 12
4 14 15 1
Array indexing- Example 1

In a 4x4 matrix change element of (4,2) to 0


For example, consider the 4-by-4 magic
square A:
A = magic(4)
A = 16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
Array indexing- Example 1

To specify and change an element present in


location (4,2) to 0 we will do the following:

A(4,2)=0

A = 16 2 3 13
5 11 10 8
9 7 6 12
4 0 15 1
Array Indexing-Example 2

List the elements in the first three rows and the


second column of A:
To refer to multiple elements of an array, use For example, consider the 4-by-4
the colon operator, which allows you to specify a magic square A:
range of the form start:end
A = magic(4)
A(1:3,2) A = 16 2 3 13
ans= 5 11 10 8
2 9 7 6 12
11 4 14 15 1
7
Array Indexing- Example 3

 Access the elements in the first through third row and


the second through fourth column of matrix A.
For example, consider the 4-by-4
r = A(1:3,2:4)
magic square A:
r=
A = magic(4)
A = 16 2 3 13
2 3 13
5 11 10 8
11 10 8
9 7 6 12
7 6 12
4 14 15 1
Array Indexing-Example 4

 Access Entire third column of matrix A

r=A(:,3) For example, consider the 4-by-4


magic square A:
A = magic(4)
r=
A = 16 2 3 13
3 5 11 10 8
10 9 7 6 12
6 4 14 15 1
15
randi() and find()

Create a matrix of random integer


A=randi(10,5) • X = randi(imax,n) returns an n-by-n matrix of
pseudorandom integers drawn from the discrete uniform
A= distribution on the interval [1,imax]
k = find(X) returns a vector containing the linear indices of each nonzero element in
array X.
6 10 1 10 9
10 1 4 2 6 If X is a vector, then find returns a vector with the same orientation as X.
1 8 3 3 6
5 9 9 2 2 If X is a multidimensional array, then find returns a column vector of the linear
indices of the result.
2 9 5 2 9
Assignment

 Create a 5-by-5 matrix that contains random


integers between 1 and 15. Find the location
of all the elements having value less than 9.
 Create a 5-by-5 matrix that contains random
integers between 1 and 15. Find the location
of all the elements in the matrix that are less
than 9 and even numbered. Replace those
elements with 0.

You might also like