Professional Documents
Culture Documents
09-Feb-13
Matrices
Vectors and Matrices
Outline
Vectors and Matrics Array Initialization Subarrays Loops with arrays/matrices
Matrices
09-Feb-13
Scalar vs Array
Scalar: indicates a variable that holds only a single value at a time.
This is compared to an array, which holds many values at once
Matrices
09-Feb-13
Array initialization
B = [1.0 2.0 3.0] creates a 1 x 3 array
Is this a column or row vector?
Array initialization
D = [1, 2, 3; 6, 5, 4] creates a 2 x 3 array
The commas are optional
E = [ ] creates a special empty array having no rows and no columns F = [ 1, 5, 6; 5, 4 ] would create ...?
An error message! All rows must have the same size, or the array is not valid
Matrices
09-Feb-13
Array initialization
MATLAB includes a very useful colon operator
Makes creating sequences very simple
The syntax is
first:increment:last
first is the first value in the series increment is how big each gap between values should be increment can be skipped last is the final value in the series my_colon = 1:2:10 my_colon = [ 1 3 5 7 9 ]
Matrices
09-Feb-13
size(arr)
Matrices
09-Feb-13
Subarrays
MATLAB allows special subarray use array = [1.1 -2.2 3.3 -4.4 5.5];
array(3) is 3.3 array([1 4]) is itself an array, [1.1 -4.4], or the first and fourth elements in array array(1:2:5) is array [1.1 3.3 5.5] or the odd elements in array
Subarrays
MATLAB allows advanced subarray indexing on the left side of an assignment
array =
1 2 3 4 5 6 7 8 9 10 11 12 The shape of the left hand side subarray index
Matrices
09-Feb-13
Test it out!
Try the following statements out in MATLAB and see what happens:
array_1 = [ 1:.2:2; 2:.2:3] array_2 = array_1(1,2:end) array_1(1, end) = 4 Change elements (1,1), (1,2), (2,1), (2,2) in one statement Change elements (1,1), (2,1), (1,5), (2,5) in one statement
Matrices
09-Feb-13
v(i)
1 3 2 7 4 2
max
maxi
0 1 ? 1 1 3 1 2 3 2 3 7 2 4 7 4 7 4
Matrices
09-Feb-13
Counting Elements
v=[1 3 2 -7 4 -2] c=0; for =1:length(v) if v(i)>0 c=c+1; end end % Repeat for the negative % Repeat for a matrix i
1 2 3 4 5 6
v(i)
1 3 2 -7 4 -2
c
0 1 2 3 3 4 1 2 3 4
Comparing Elements
v1=[1 3 2 7 4 -2] v2=[5 3 4 1 2 -2] for i=1:length(v1) if v1(i)>v2(i) v(i)=1; elseif v1(i)<v2(i) v(i)=-1 else v(i)=0; end end i
1 2 3 4 5 6
v1(i)
1 3 2 7 4 -2
v2(i)
5 3 4 1 2 -2
v(i)
-1 0 -1 1 1 0
Matrices