Question about syntax (commas and colons)
9 views (last 30 days)
Show older comments
Lets say I have a matrix such as ones(6). When I give the command a(:,3:4) = 2 it changes the 3rd and 4th rows into 2s. But I do not understand how the a(:,3:4) could be interpreted into the 3rd and 4th row. Similarly in a(3:4,:) = 2, how can we understand that it means change the 3rd and 4th column to 2s?
Moreover, why is the comma and the last colon necessary? What are the roles of the commas and colons?
0 Comments
Answers (1)
rantunes
on 14 Mar 2015
Hey,
When I do a(:,3:4) = 2, the 3rd and 4th columns turn into 2 as should be expected. The other command a(3:4,:) = 2 , changes the 1s into 2s in the 3rd and 4th rows. This happens since a = ones(6) is a matrix 6x6 with six rows and six columns.
By convention, each element of the matrix is found writing a(i,j) where i is the row and j is the column. So if you say a(2,3) = 2 , then the element in the 2nd row and 3rd column will be replaced by 2. From here, it it is obvious the role of the commas.
The colons, for example in a(:,2) = 1 , basically say that "for all the rows" (notice that we have : in the rows argument) put in the 2nd column the number 1.
When you use something like a(:,3:4) = 2 , we still have the same case as "for all the rows". The difference here is that we establish a columns range (between the 3rd and the 4th).
As an example a(1:2,3:4) = 3 puts the number 3 in the interval selected: the intersection between the 1st and 2nd rows and 3rd and 4th columns.
In addition, the command a(:,:) = 2 basically changes all the matrix elements to 2.
Greets.
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!