Professional Documents
Culture Documents
Chapter 2
Chapter 2
Chapter 2
Array
The array is a fundamental form that MATLAB uses to store and manipulate data.
An array is a list of numbers arranged in rows and/or columns.
>>x = 10 : 1 : 100
How can you create an array with numbers from 100 to 1 in decreasing order?
Concatenating 1D Arrays
x = 1 : 5;
y = 100 : 105;
z = [x, y, x] x, y and x are concatenated into one array
Z=
1 2 3 4 5 100 101 102 103 104 105 1 2 3 4 5
ARRAY ADDRESSING
Vector:The address of an element in a vector is its position in the row (or column).
x = 10 : -1 : 1;
y = x(3)
What are the outputs of the following commands?
x = 10 : -1 : 1; 2) x = 10 : -1 : 1;
1) y = x(end)
y = x([3,9,4])
x = 10 : -1 : 1;
x(2) = 10;
USING A COLON : IN ADDRESSING ARRAYS
A colon can be used to address a range of elements in a vector or
a matrix.
For a vector:
va(:) Refers to all the elements of the vector va (either a row or a
column vector).
va(m:n) Refers to elements m through n of the vector va.
Example:
Adding elements to a vector:
We can erase(delete) elements of an vector
x = 10 : -1 : 1;
x(2) = []
x = 10 : -1 : 1;
x(2 : 4) = []
CREATING A TWO-DIMENSIONAL ARRAY (MATRIX)
variable_name = [1st row elements; 2nd row elements; 3rd
row elements; ... ; last row elements]
The zeros, ones and, eye Commands
zeros(m,n), ones(m,n), and eye(n)
THE TRANSPOSE OPERATOR( ’ )
The transpose operator, when applied to a vector,
When applied to a matrix, it switches the rows (columns) to
columns (rows).
2D Array Addressing:The address of an element in a matrix is its position,
defined by the row number and the column number where it is located.
y = [1 2 3; 4 5 6; 7 8 9];
y(2, :) = [];
y(: , [1 3]) = [];
y
BUILT-IN FUNCTIONS FOR HANDLING ARRAYS
Problems
1) Using the colon symbol, create a row vector (assign it to a variable named Fives) with
five elements that are all 5.?
2)
Answers
>>Fives(1:5)=5
>>Fives =
5 5 5 5 5
>>D=[zeros(3,4) [8:-1:6]']
>>D =
0 0 0 0 8
0 0 0 0 7
0 0 0 0 6