In all the following questions you are expected to have an "elegant" solution, not a brute force one. No if
statements or loops. Unless where specifically noted, no MATLAB® functions are to be used.
- Find out what the command
diag
does. (We already learned aboutones
,zeros
, andsum
, but if you are unsure, look them up as well.) Usingsum
anddiag
, find the sum of the diagonal of a matrix. (For example,A
in the next question.) - Let
A=magic(6)
. What expression will give you the \(2\times2\) submatrix of elements in the upper left corner? How about lower right? Can you write an expression that will also work for any other matrixA
, for exampleA=magic(10)
? - Find the sub-matrix of elements of
A
whose both coordinates are odd. - With no MATLAB functions, write the matrix
A
"flipped" right to left. Up to down. - Get the sum of the "anti diagonal" of the magic square by a simple expression using
sum
,diag
and the colon (:
) notation. - Let
x = [2 5 1 6]
. Add 3 to just the odd-positioned elements (resulting in a 2-vector). Now write the expression that adds 3 to the odd-positioned elements and puts the result in the even positions of the originalx
vector. - Let
y = [4 2 1 3]
. Think of y as a specific reordering (permutation) of the numbers \(\{1, 2, 3, 4\}\). "4 goes to 1, 2 remains, 1 goes to 3 and 3 goes to 4." Usey
to reorder the elements ofx
in the same manner. (The result should be[6 5 2 1]
.) - What is the vector that corresponds to the permutation of n elements that takes every element one position to the left, except for the first element, which goes to the end?
- (Bonus) The inverse of a permutation
y
is a permutationz
that, when combined withy
(in either order) gives the original (non-permuted) elements. Given a permutation vector (asy
is in the previous question), find the vectorz
which corresponds to the inverse ofy
. - Experiment with assignments such as
b(1:3,1:2:4)=1
. Make a "checkerboard" matrix: an 8-by-8 matrix whose cell \(a(i,j)\) equals 1 if \(i+j\) is odd and 0 if it is even. (Of course, do not use loops orif
statements!) If you like, use the functionspy
orpcolor
to "see" the checkerboard that you created. (Tricky. Do it in two commands, not one. If you want to do this with one command you may useones
. Also possible usingmod
andreshape
.) - Recall that a matrix (such as
A
) can also be referenced using a single coordinate:A(3)
. Remind yourself how this coordinate is related to the original matrix. - Use the single index reference to a matrix in order to extract the diagonal of a 5-by-5 matrix. (Do not use the function
diag
.) Do the same to extract the "anti-diagonal".