1 / 12

2-D Arrays (Matrices)

2-D Arrays (Matrices). 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)

Download Presentation

2-D Arrays (Matrices)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 2-D Arrays (Matrices)

  2. 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

  3. Accessing Elements >> m(2, 1) ans = 21 >> m(2, 3) ans = 23 >> m(4, 1) ??? Index exceeds matrix dimensions.

  4. 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

  5. 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

  6. 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

  7. 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

  8. 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

  9. 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

  10. 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

  11. 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

  12. 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

More Related