Vg101 Recitation I TAs
Vg101 Recitation I TAs
Agenda Vectors matrices Flow control Example1 (addGeneral) ·Plotting with Matlab ·Example2(regPloy)
• Vectors & matrices • Flow control • Example1 (addGeneral) • Plotting with Matlab • Example 2 (regPloy) Agenda
Operators (arithmetic) addition subtraction multiplication division power franspose ★ element-by-element mult element-by-element div element-by-element power
Operators (arithmetic) + addition - subtraction * multiplication / division ^ power ’ transpose .* element-by-element mult ./ element-by-element div .^ element-by-element power
Generating Vectors y a:step:b y linspace(a,b,n) y logspace(a,b,n) >>y logspace(1,2,6) y= 10.0000 15.8489 25.1189 39.8107 63.0957100.0000
Generating Vectors • y = a:step:b • y = linspace(a, b, n) • y = logspace(a, b, n)
Generating Matrices zeros(M,N)MxN matrix of zeros -ones(M,N) MxN matrix of ones ·rand(M,n) MxN matrix of uniformly distributed random numbers on (0,1) ·Direct define y=[123;456;789] y=[1,2,3:4,5,6,7,8,9]
Generating Matrices • zeros(M,N) MxN matrix of zeros • ones(M,N) MxN matrix of ones • rand(M,N) MxN matrix of uniformly distributed random numbers on (0,1) • Direct define y = [1 2 3;4 5 6;7 8 9] y = [1,2,3;4,5,6;7,8,9]
Matrices To delete a row or column 9>>A(3,:)=[] 之>A(:,1)=[] To define a sub-matrix >>B=A(L23].[12]) To concatenate matrices >>B=[A,10*A:-A,[100:010:001]
Matrices • To delete a row or column >> A(3, :) = [ ] >> A(:, 1) = [ ] • To define a sub-matrix >> B = A([2 3],[1 2]) • To concatenate matrices >> B = [A, 10*A; -A, [1 0 0; 0 1 0; 0 0 1]]
Flow Control if if...e nd if else ..end if ..elseif ..else ..end 。while.end loop ·for..end loop switch...end statement
Flow Control • if • – if ... end • – if ... else ... end • – if ... elseif ... else ... end • while…end loop • for...end loop • switch…end statement
Example 1 Write a function, c=addGeneral(a,b). which can add two matrices with different sizes together.Before adding,you should extend the matrices with zeros to the same size
Example 1 • Write a function, c=addGeneral(a,b), which can add two matrices with different sizes together. Before adding, you should extend the matrices with zeros to the same size
Sample input Sample output a=[123:456;789] a= >>c=addGeneral(a,b) 3 6 2 4 3 9 7 9 6 >b=[12;34] 7 8 9 b 1 2 3 4
Sample input >> a=[1 2 3;4 5 6;7 8 9] a = 1 2 3 4 5 6 7 8 9 >> b = [1 2;3 4] b = 1 2 3 4 Sample output >> c = addGeneral(a,b) c = 2 4 3 7 9 6 7 8 9
function c addGeneral(a,b) [row a,col a]size(a); [row b,col b]size(b); if row a row b if col a col b b [b,zeros(row b,col a col b)]; else a [a,zeros(row a,col b col a)]; end b [b;zeros (row_a row _b,max(col_a,col_b))]; else if col a col b b [b,zeros (row b,col a col b)]; else a [a,zeros(row a,col b col a)]; end a [a;zeros(row b -row a,max(col a,col b))]; end c=a+b;