To start, let us examine the 6 x 6 matrix created by
magic(6) in MATLAB, and name it M:

In this article, we will accomplish these main tasks:
1) Find the sum of each row of M.
2) Find the sum of each column of M.
3) Find the sum of the diagonal entries of M, i.e., M(k, k), for k = 1, 2, 3, 4, 5, 6, where k is the current index.
4) Find the sum of the anti-diagonal entries of M, i.e., M(1, 6), M(2, 5), M(3,4), M(4,3), M(5,2), M(6,1).
5) Find a logical array showing which entries of M are < 8.
6) Find a logical array showing which entries of M are >= 22.
7) Set entries of M that meet the conditions in 5) or 6) above to be 100.
Let’s start with 1); finding the sum of each row of our magic matrix M.
We can use the sum() function, paired with the Dimension Argument 2:

What does the rowSum line mean? It is important to understand the arguments we put into sum(). Essentially, we told the <<compiler>> to sum across the second dimension (the Dimension Argument of 2) of the matrix assigned to M. With this line, MATLAB takes the matrix M, then searches across the second dimension, which is the columns.
Using the same logic for 2), we can take the sum across the Dimension Argument 1, the rows, to get the sum of the columns:

Now we can move onto 3); find the sum of the diagonal entries of M, i.e., M(k, k), for k = 1, 2, 3, 4, 5, 6, where k is the current index. We can use the conveniently available function trace():

And conversely, we can accomplish 4); Find the sum of the anti-diagonal entries of M, i.e., M(1, 6), M(2, 5), M(3,4), M(4,3), M(5,2), M(6,1).
We will need help from the fliplr() function:


Lastly, we must accomplish the following three:
5) Find a logical array showing which entries of M are < 8.
6) Find a logical array showing which entries of M are >= 22.
7) Set entries of M that meet the conditions in 5) or 6) above to be 100.
Thinking about this from a regular programmer’s point of view, it would make sense to make the <<compiler>> parse through each <<number>> until it finds one smaller than 8, or one that is 22 or higher, then set the value at that index to 100. MATLAB will do this for us in a very simple line of code:

Which will yield us the following results:


We must notice that in the logical arrays, there are 0s (zeroes) where the value does not satisfy the condition, and 1s (ones) where it does. All that needs to be done is change wherever there is a 1 to a 100. We can do that very simply with one line:

Which will yield us the result we need:

You can manually check that all indices that had a 1 in the logical matrices have been changed to 100s.