Accessing Matrix Elements
We already say in the previous lecture that you can access the (2,3)th element of a matrix a with the notation
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
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:
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:
Of course, if by the manipulation you get an illegal expression, matlab will complain:
The 1:end construction is so useful that Matlab has a further shorthand for it:
Means the same as B(2,1:end). So, one should think of the bare colon (:) as meaning "everything".
Non-contiguous element access
The 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])
Assigning into submatrices
Just 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]
Matlab 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 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.