[MATLAB logo] Exploiting MATLAB's Data Structures

Solution #1 - Rank of Magic Squares

Is there any pattern to the rank of magic squares? In this problem you will create and manipulate the contents of a cell array to find out.

Goal: Create a simple sequence of statements to determine the rank of a series of magic squares. Bar plot the results and see if you notice any patterns. Solve the problem in stages and use a cell array to hold the intermediate results.

Key concepts: creating cell arrays, applying functions to the elements of a cell array, converting a cell array into a numeric array.

Key functions: { }, rank, bar

Solution

  1. Put magic squares from size 1:50 into a cell array named ms. Use the cell indexing syntax {i} to place each magic square into a separate cell.
    for i= 50:-1:1
    ms{i} = magic(i);
    end
    The loop is run backwards to avoid a preallocation step.
  2. Calculate the rank for each of these and assemble these ranks into a double vector named r. This operation could be done in two steps (first apply the function rank to each cell and then pull out each cell to create the desired double vector r) but is easier to read and more efficient to apply the function and create the vector in one step.
    for i=50:-1:1
    r(i)= rank(ms{i});
    end
  3. Use bar to display r
    bar(r)

Alternate solution (without using cell arrays)

  1. Create the vector r with a FOR loop
    for i= 50:-1:1
    r(i) = rank(magic(i));
    end
    The loop is run backwards to avoid a preallocation step.
  2. Use bar to display r
    bar(r)

Copyright © 1997 The MathWorks, Inc.
clay@mathworks.com
$Revision$ $Date$