3-Creating Arrays - For Students - Mid Term
3-Creating Arrays - For Students - Mid Term
3-Creating Arrays - For Students - Mid Term
with applications
3. Creating Arrays
Context of This Chapter
• Array: fundamental form that MATLAB uses to store and
manipulate data
• A list of numbers arranged in rows and/or columns
variable_name = [m : q : n] or variable_name = m : q : n
5 10 9 8
A = 18 1 7 11
29 14 3 6
• A(1,1)=5, A(2,3)=7
Array Addressing- Matrix
• Size(A)
– Returns a row vector [m, n], where m and n are the size mxn of the
array A.
>> A=[6 1 4 0 12; 5 19 6 8 2]
A=
6 1 4 0 12
5 19 6 8 2
>> size (A)
ans =
2 5
Built-In Functions for Handling
Arrays
• reshape(A,m,n)
– Creates a m by n matrix from the elements of matrix A.
– The elements are taken column after column.
– Matrix A must have m times n elements.
>>A=[5 1 6; 8 0 2];
A=
5 1 6
8 0 2
>> B=reshape(A,3,2)
B=
5 0
8 6
1 2
• diag(v)
– When v is a vector, creates a square matrix with the elements of v in the diagonal.
>> v=[7 4 2];
>> A=diag(v)
A=
7 0 0
0 4 0
0 0 2
Built-In Functions for Handling
Arrays
• diag(A)
– When A is a matrix, creates a vector from the diagonal elements of A.
>>A=[1 2 3; 4 5 6; 7 8 9]
A=
1 2 3
4 5 6
7 8 9
>> vec=diag(A)
vec =
1
5
9
Create a Matrix
• Using the ones and zeros commands, create a 4x5
matrix in which the first two rows are 0s and the
next two rows are 1s.