Tuesday 10 June 2014

Unpacking colons to indices


I wish I'd known MATLAB had... X(':')

  • The colon character can be used as an index, to mean a whole row/column/slice etc. But you can use the quoted character too!
  • Why would this ever be useful?  When using cell-expansion indexing.

Example:

Let us say that you have a line that extracts a single vector from a matrix, but sometimes you need the first row, and other times you need the first column.
i.e.. sometimes you want Y=X(1,:), and other times you want Y=X(:,1).
  •   Can this be done without an IF statement?
  •   Yes:
         indices = {':',1};
         indices = fliplr(indices);
         Y=X(indices{:})
  • This works because indices{:} expands to a comma-separated list, in this case 1 and ':'.
  • Expansion of cell arrays to these lists can be used as input to functions, or indices of an array.
  • This is also how varargin{:} works.  

No comments:

Post a Comment