In: Computer Science
MATLAB:
Matrix M = [ 0 2 3 5; 7 3 8 4 ]
Write one command that stores all of the rows of columns 1, 2, and 3 of M into a matrix named M2.
Hello, so, we have our matrix M, given in the question -
M = [ 0 2 3 5; 7 3 8 4 ]
let us see how it will look like -
M will look like
1st 2nd 3rd 4th
column column column column
[ 0 2 3 5
7 3 8 4 ]
Now after storing all of the rows of columns 1, 2, and 3 of our given matrix M, our desired matrix will look like
M2, which is our desired matrix =
1st 2nd 3rd
column column column
[ 0 2 3
7 3 8 ]
So, you see, only rows of the column 1, 2, and 3 are there.
Now the one-line command, which we can use to make it work is -
M2 = M(:, 1:3)
It simply means that we are making a matrix M2, which will store all the row values of matrix M, and column values starting from index or position 1st to 3rd.
In M(:, 1:3), M is our matrix, and the first parameter after the parenthesis is the row value, where we have specified ':', which means all the rows (':' means all the values), and the second parameter separated by a comma (,) is our column value, which we are giving '1:3', means take column values from index 1 to 3, or better say take values from 1st column to 3rd column.
So, our full code will look like this -
M = [ 0 2 3 5; 7 3 8 4 ]
M2 = M(:, 1:3)
The result -
Hope you like my answer, and if you like, then please do upvote this answer, and also hope that you now know how to do it, and if you feel that you are stuck at some point, then please do comment and I will clarify it as soon as possible.
Happy Learning. Thank you.