« Earlier2 items total Later »

Comma seperated lists

Matlab has some extremely nice notation for working with lists of items and indexing through lists of items. The simplest way to work with CSLs is to use cell arrays. Cells arrays are lists and you can build one as below.

a =  { 'cat' 'dog' 'cow' }


Now what can you do with this list? First of all you can index individual elements.

>> a{1}
ans =
   'cat'
>> a{2}
ans =
   'dog'


You can index a range of elements
>>a{1:2}
ans =
  'cat'
ans =
  'dog'

In the case what has been returned above is a comma seperated list, effectivly a tuple of answer, not a single object but a set of answers.

You can regroup the CSL using a number of concatenation techniques.

Using {}
>> { a{1:2} }
ans =
 'cat' 'dog'


Using []
>> { a{1:2} }
ans =
 'catdog'


Using () to provide function arguments
>> a = { 1 2 };
>> b = sum( a{1:2} )
b =
 3





Collect multiple return values into a cell array.

The min function can return two values, Y and I. Y being the min values and I being the index of the min value. Normally you would call it like this.

[y i] = min(X);


However sometimes this is not convienient. What if you don't know before hand how many left hand values you wish to collect. Imagine you wanted to wrap up a call to feval with your own feval.

function varargout = my_feval(varargin)
   ...
   % Do some stuff
   ...
   varargout= feval(varargin);
   ...
   % Do some stuff
   ...
end


will not work. You need to do some fancy indexing.

function varargout = my_feval(varargin)
   ...
   % Do some stuff
   ...
   [varargout{1:nargout}] = feval(varargin);
   ...
   % Do some stuff
   ...
end

« Earlier2 items total Later »




Sponsored by

Sole Central

Your one stop shop for Birkenstock and Crocs shoes and sandles.