ENGR113 - Lecture 4- Creating Arrays-A
ENGR113 - Lecture 4- Creating Arrays-A
using Matlab
Creating Arrays-A
Arrays: Introduction
Generally speaking:
• An array is a systematic arrangement of objects, usually in rows
and columns ….
Wikipedia
Creating a One-Dimensional Array (Vector)
• An array is MATLAB's basic data structure
• Can have any number of dimensions. Most common are
• vector - one dimension (a single row or column)
• matrix - two or more dimensions
• Arrays can have numbers or letters
• To create a row vector from known numbers, type variable name, then equal sign,
then inside square brackets, numbers separated by spaces and/or commas
variable_name = [ n1, n2, n3 ]
>> z = -3:7
z = -3 -2 -1 0 1 2 3 4 5 6 7
>> z=100*ones(3,4)
z =
100 100 100 100
100 100 100 100
100 100 100 100
The Transpose Operator
Transpose a variable by putting a single quote after it, e.g., x'
• In math, transpose usually denoted by superscript "T", e.g., xT
• Converts a row vector to a column vector and vice-versa
• Switches rows and columns of a matrix, i.e., first row of original becomes first
column of transposed, second row of original becomes second column of
transposed, etc.
>> aa=[3 8 1]
aa = 3 8 1
>> bb=aa'
bb = 3
8
1
Array Addressing
Can access (read from or write to) elements in array (vector or matrix)
individually or in groups
• Useful for changing subset of elements
• Useful for making new variable from subset of elements
Address of element is its position in the vector
• "address" often called index
• Addresses always start at 1 (not 0)
• Address 1 of row vector is leftmost element
• Address 1 of column vector is topmost element
• To access element of a vector represented by a variable, follow variables name by
address inside parentheses, e.g., v(2)=20 sets second element of vector v to 20
Array Addressing: Vector
>> VCT=[35 46 78 23 5 14 81 3 55]
VCT = 35 46 78 23 5 14 81 3 5
>> VCT(4)
ans = 23
>> VCT(6)=273
VCT = 35 46 78 23 5 273 81 3 5
>> VCT(2)+VCT(8)
ans = 49
>> VCT(5)^VCT(8)+sqrt(VCT(7))
ans = 134
Array Addressing: Matrix
Address of element in a matrix is given by row number and column number.
Address often called index or subscript
• Addresses always start at 1 (not 0)
• Row 1 is top row
• Column 1 is left column
• If variable ma is a matrix, ma(k,p) is element in row k and column p
>> MAT=[3 11 6 5; 4 7 10 2; 13 9 0 8]
Column 1
MAT = 3 11 6 5
Element in
row 3 and
4 7 10 2
column 1 13 9 0 8 Row 3
>> MAT(3,1)
ans = 13
Using A Colon : In Addressing Arrays
>> F=A(1:3,2:4) Columns two through four of rows one through three
F = 3 5 7
4 6 8
6 9 12
Can replace vector index or matrix indices by vectors in order to pick out
specific elements. For example,
m([a b],[c:d e]) returns columns c through d and column e of rows
a and b for matrix m
>> A=[10:-1:4; ones(1,7); 2:2:14; zeros(1,7)]
A = 10 9 8 7 6 5 4
1 1 1 1 1 1 1
2 4 6 8 10 12 14
0 0 0 0 0 0 0