Lecture 2Accessing Matrix ElementsSubmatricesWe already say in the previous lecture that you can access the (2,3)th element of a matrix a with the notation
>> a(2,3) This gives the entry of a in the second row and the third column.
We can also gain access to several elements at the same time. Try for example: >> a(2, [1 2]) >> a([3 4], 3) >> a([2 3], [3 4]) These commands extract a submatrix of a with the corresponding set of rows and columns. It is often useful to extract a whole row or column of a given matrix. Assuming that B has 10 rows, we can extract the second column of B with the command >> B(2,1:10) Using the column notation instead of spelling out [1 2 3 4 5 6 7 8 9 10]. In fact, there is more shorthand to be learned here. First, we can replace the 10 with the keyword end: >> B(2,1:end) This keyword gets replaced by the largest number allowed for that place. So if it is used in the rows it will be replaced wit the number of rows, if in the columns, with the number of columns. It is useful to know that one can manipulate it as one would any other variable: >> B(2,1:end-1) >> B(2,1:end/2) Of course, if by the manipulation you get an illegal expression, matlab will complain:
>> B(2,1:end+1) >> B(2,sin(end):end) The 1:end construction is so useful that Matlab has a further shorthand for it: >> B(2,:)
Means the same as B(2,1:end). So, one should think of the bare colon (:) as meaning "everything". Non-contiguous element accessThe elements of the matrix that we access do not have to be contiguous:
>> a(3,[2 4 6]) >> a([2 4], [1 3]) They don't have to be in increasing order:
>> a(3,[2 6 4]) >> a([4 1], [3 2]) Nor do they have to only appear once:
>> a(3,[2 2 4 4 1 1 1]) >> a(3*ones(1,3),2*ones(1,10))
Exercises:
Assigning into submatricesJust as in the reference and assignment of single numbers into matrices, we can also assign new values into complete submatrices. The only thing that needs to be checked is that the matrix on the right of the equal sign has the same dimension as the matrix referenced on the left: >> a([2 3],[1 4]) =[1 2 ;3 4] >> a(1,1:4)=2:5 Scalar expansionMatlab has a nice time-saving notation. If an operator requires a matrix of a known size and instead is given a scalar (i.e a number). It "expands" the scalar into a full matrix of the required size. This is quite cumbersome to say...much better to show examples: >>1:10.^2 >>2.^1:10 >>[1 2; 3 4] + 5 In these three cases, the relevant operator is looking for a matrix of the same size as the one it already has on the other side, but instead it finds a number. So Matlab pretends as if the matrix of the expected size is there with each of its entries equal to the number. Exercises
|