An interactive introduction to MATLAB

(Jeff_L) #1
1.4variables and arrays 11

Read MATLAB error messages!
??? Error using ==> mtimes
Inner matrix dimensions must agree.
This error message example usually indicates you tried to perform a matrix
operation when you intended an element-by-element operation. You should
check your code for a missing dot operator.
You can access individual elements, entire rows and columns, and subsets of
matrices using the notationmatrix_name(row,column). Listing 1.12 demon-
strates how to access elements in a matrix. Square brackets[ ]
are used when creating
vectors, arrays and
matrices, and round
brackets( )when
accessing elements in
them.

Listing 1.12: Accessing elements of matrices
1 >> w = [1 2 3 4; 5 6 7 8; 9 10 11 12]
2 w =
3 1 2 3 4
4 5 6 7 8
5 9 10 11 12

7 >> size(w)
8 ans =
9 3 4

11 >> w(1,1)
12 ans =
13 1


15 >> w(3,1)
16 ans =
17 9


19 >> w(3,:)
20 ans =
21 9 10 11 12


23 >> w(2,4) = 13
24 w =
25 1 2 3 4
26 5 6 7 13
27 9 10 11 12


29 >> v = w(1:2,2:3)
30 v =
31 2 3
32 6 7


34 >> z = w([2,3],[2,4])
35 z =
36 6 13
37 10 12

Free download pdf