130 likes | 288 Vues
This guide covers the basics of working with 2-D arrays (matrices) in programming. It includes creating matrices, accessing and modifying elements, and executing operations like addition. Examples demonstrate how to initialize matrices using values or functions (zeros, ones), access specific elements, and modify them. It also addresses common errors such as exceeding matrix dimensions. Lastly, it provides an approach for summing two matrices of different sizes while treating missing elements as zeros.
E N D
Creating 2-D Arrays m = [ 11 12 13 21 22 23 31 32 33]; or >> m = [11 12 13; 21 22 23; 31 32 33] m = 11 12 13 21 22 23 31 32 33
Accessing Elements >> m(2, 1) ans = 21 >> m(2, 3) ans = 23 >> m(4, 1) ??? Index exceeds matrix dimensions.
Modifying Elements >> m(1, 3) = 1133 m = 11 12 1133 21 22 23 31 32 33 >> m(5, 6) = 56 m = 11 12 1133 0 0 0 21 22 23 0 0 0 31 32 33 0 0 0 0 0 0 0 0 0 0 0 0 0 0 56
zeros function >> z = zeros(3) z = 0 0 0 0 0 0 0 0 0 >> z = zeros(2, 4) z = 0 0 0 0 0 0 0 0 >> zeros(1, 5) + (1:5) ans = 1 2 3 4 5
ones function >> ones(3) ans = 1 1 1 1 1 1 1 1 1 >> ones(1, 5) + (10:14) ans = 11 12 13 14 15
Getting Columns and Rows >> m = [11 12 13; 21 22 23; 31 32 33] m = 11 12 13 21 22 23 31 32 33 >> m(1, :) ans = 11 12 13 >> m(3, :) ans = 31 32 33 >> m(:, 2) ans = 12 22 32
size function >> m = ones(4, 7); >> size(m) ans = 4 7 >> [rsize csize] = size(m) rsize = 4 csize = 7 >> size(m(1, :)) ans = 1 7 >> length( m(1, :)) ans = 7 >> length( m(:, 1)) ans = 4
Programming Example : max function max=x(v) max = -inf; for i = 1:length(v(1, :)) for j = 1:length(v(:, 1)) if (v(i, j) > max) max = v(i, j); end end end
Adding two matrices • Add corresponding elements of two matrices • Allow matrices to be of any sizes • Assume that the missing elements are 0. • Example: for [1;2] and [10, 20], produce: 11 20 2 0
Adding Matrices Example >> v1 = ones(2,3) v1 = 1 1 1 1 1 1 >> v2 = ones(4, 2) v2 = 1 1 1 1 1 1 1 1 >> x(v1, v2) ans = 2 2 1 2 2 1 1 1 0 1 1 0
function sum=sum_matrices(v1, v2) nrows1 = length(v1(:, 1)); nrows2 = length(v2(:, 1)); ncols1 = length(v1(1, :)); ncols2 = length(v2(1, :)); nrows = max([ nrows1 nrows2 ]); ncols = max([ ncols1 ncols2 ]); sum = zeros(nrows, ncols); for i = 1: nrows for j = 1: ncols n1 = 0; n2 = 0; if ( i <= nrows1 && j <=ncols1) n1 = v1(i, j); end if ( i <= nrows2 && j <=ncols2) n2 = v2(i, j); end sum(i, j) = n1 + n2; end end