Matlab Arrays Vectors Initialize vectors either like V
Matlab Arrays
Vectors • Initialize vectors either like : – V = [1 2 3 4 5], or : – V = [1, 2, 3, 4, 5] • In order to create a column vector : – V = [1; 2; 3; 4; 5] • You can put any numeric expression for the individual elements of your vector
Accessing Vector Elements • Given v = [1 2 3 4 5], or v = [1; 2; 3; 4; 5] – V(1) returns 1, – V(2) 2, … v(5) 5 – v(6) ? ? ? Index exceeds matrix dimensions. • v(0) ? ? ? Subscript indices must either be real positive integers or logicals.
Changing Vector Elements >> v(3) = 8 v= 1 2 8 4 5 >> v(0) = 0 ? ? ? Subscript indices must either be real positive integers or logicals. >> v(7) = 128 v= 1 2 8 4 5 0 128
Strings are also vectors … >> st = 'abcde' st =abcde >> st(0) ? ? ? Subscript indices must either be real positive integers or logicals. >> st(3) ans =c >> st(3) = 'X' st =ab. Xde >> st(10) = 'O' st =ab. Xde O
Transpose Operator >> [1 2 3]' ans = 1 2 3 >> [1; 2; 3]' ans = 1 2 3
Vector length >> length(v) ans = 7 >> length(v') ans = 7 >> v(length(v)) ans = 128 >> v(end) ans = 128
Vector operations • Given vector v = [1 2 3 4 5] >> v + 10 ans = 11 12 13 14 15 >> v * 2 ans = 2 >> v' + 10 ans = 11 12 13 14 15 4 6 8 10
Vector operations • Given vectors v = [1 2 3 4 5], v 2 = [10 20 30 40 50] : >> v + v 2 ans = 11 22 33 44 55 >> v 2 -v ans = 9 18 27 36 45 >> v + v 2' ? ? ? Error using ==> + Matrix dimensions must agree.
Vector Operations >> v * v 2 ? ? ? Error using ==> * Inner matrix dimensions must agree. >> v / v 2 ans = 0. 1000 >> v(3) = 6 v= 1 2 >> v / v 2 ans = 0. 1164 6 4 5
Element-by-element operations >> v. * v 2 ans = 10 40 >> v. / v 2 ans = 0. 1000 90 160 250 0. 1000 >> v. + v 2 ? ? ? v. + v 2 | Error: "identifier" expected, "+" found. >> v + v 2 ans = 11 22 33 44 55 0. 1000
Functions that Accept Vectors >> log(v) ans = 0 0. 6931 1. 0986 1. 3863 1. 6094 >> sin(v) ans = 0. 8415 0. 9093 0. 1411 -0. 7568 -0. 9589 >> round(10 * log(v)) ans = 0 7 11 14 16
Creating Vectors by Ranges >>v = 1: 5 v= 1 2 3 >> v = 11: 16 v = 11 12 13 4 5 14 15 16 >> v = 5: 1 v= Empty matrix: 1 -by-0 • in general : first: last [first, first+1, first+2, … , last-1, last]
Specifying an Increment >> v = 10: 50 v = 10 20 30 40 50 >> v = 50: -10: 10 v = 50 40 30 20 10 >> v = 10: -10: 50 v= Empty matrix: 1 -by-0 >> v = 10: 20: 50 v = 10 30 50 >> v = 10: 15: 50 v = 10 25 40
Linspace function • LINSPACE(X 1, X 2) generates a row vector of 100 linearly equally spaced points between X 1 and X 2. • LINSPACE(X 1, X 2, N) generates N points between X 1 and X 2. >> linspace(10, 20, 5) ans = 10. 0000 12. 5000 15. 0000 17. 5000 20. 0000
Plotting >> x = linspace(0, 4 * pi, 100); >> y = sin(x); >> y 2 = (sin(x)). ^ 2; >> y 3 = y + y 2; >> plot(x, y);
Plotting … >> plot(x, y 2); >> plot(x, y 3);
>> plot(x, y, x, y 2, x, y 3); >> title('An interesting plot'); >> xlabel('x'); >> ylabel('y'); >> legend('sin(x)', 'sin(x)^2', 'sin(x) + sin(x)^2'); Multiple Plots
- Slides: 18