MATLAB TUTORIAL - PART IV
Since we will be dealing with matrices a lot, it is always good to learn some matrix and vector operations. And one of the mostly used operations is the transpose operation, where if applied to a vector, it will switch row(column) to column(row), and when it is applied to a matrix, it will switch rows(columns) to columns(rows). And it is applied when typing ‘ to the variable as shown in the example below:
>> a3
a3 =
1 3 5
1 3 4
23 41 59
>> a3′
ans =
1 1 23
3 3 41
5 4 59
And since the basic elemet of MATLAB is the array, it is good to master the addressing of its elements. You can address individual elements or subgroups in a matrix or vector.
In the case of vectors, all you have to do is to execute vector(k) where k is the position of the element that we want. While in the case of matrices, we have to specify the number of row and the number of column of the element wthat we want. so Matrix(k,p) will give you the element at the intersection between row k and column p. Of course you can change the value at that location by executing:
Vector(k)=newvalue
Matrix(k,p)=new value
Here is an example to address an element in a vector:
v =
2 3 5 6 77 7
>> v(3)
ans =
5
and same thing can be done on a matrix using the above appropriate notation.
Addressing group of elements is a bit tricky, but when you understand it, it is really easy.
For vectors:
- V(:) refers to all the elements of vector V
- V(m:n) refers to the range of elements from location m through location n
For Matrices:
- M(:,n) refers to elements of column n
- M(m,:) refers to elements in row m
- M(:,l:n) refers to elements in all rows between column l to column n
- M(l:n,:) refers to elements in all columns between row l to row n
- M(i:j,l:n) refers to elements in row i through j and columns l through n
Below are some examples to pratice so you will grasp the concept:
>> V=[2 3 4 55 33 95 55 ]
V =
2 3 4 55 33 95 55
>> V(3:5)
ans =
4 55 33
a3 =
1 3 5 4
1 3 4 5
23 41 59 4
3 4 55 33
>> a3(2:3,3:4)
ans =
4 5
59 4
If you want to create another vector U which is a subset of vector V where U consists of elements of V at locations 2,4 and from 5 to 7 , you can execute the following command:
V =
2 3 4 55 33 95 55
>> U=V([2,4,5:7])
U =
3 55 33 95 55
And we can apply the same concept to matrices. Assume the following matrix:
a3 =
1 3 5 4
1 3 4 5
23 41 59 4
3 4 55 33
and we want to extract row 1 and 3, and column 1 , and from 3 to 4. This is done by the following command:
>> a4=a3([1,3],[1,3:4])
a4 =
1 5 4
23 59 4
In the coming tutorial, one of the things that we will learn is to add elements to arrays. Click on the link below to view the next tutorial.
Filed under: MATLAB

Leave a Reply
You must be logged in to post a comment.