Code covered by the BSD License  

Highlights from
vars2cell

vars2cell

by

 

11 Sep 2012 (Updated )

% PURPOSE: Convert selected variables in matlab workspace to the cell's columns

vars2cell(varargin)
function cellA = vars2cell(varargin)
% PURPOSE: Convert selected variables in matlab workspace to the cell's columns
% -----------------------------------------------------------------------------
% SYNTAX: 
%         (1) vars2cell(var1, var2)
%         (2) vars2cell(var1, var2, newvarnamelist)
% -----------------------------------------------------------------------------
% OUTPUT: 
%       (1) cellA: NxM --->a cell containing M columns. Each column include
% a head and its body.

% -----------------------------------------------------------------------
% INPUT: 
%       (1) var1, var2...,  the variables (var1, var2, .., varM) in matlab workspace s been transform to columns of the cell
%        (2) newvarname: 1xM ---> M string as new head for the column.


% -----------------------------------------------------------------------
% LIBRARY: 
% -----------------------------------------------------------------------
% SEE ALSO: cell2vars,  
% -----------------------------------------------------------------------
% REFERENCE: assigni, eval
% -----------------------------------------------------------------------
% written by:
%  Lin Renwen
%  <linrenwen@gmail.com>

% Version 1.0 [2012-9-8 13:47:28]
% Version 1.1 [2012-9-12 20:46:04] Modified the example. Thanks for Simon's suggestion!

%=============================================
% EXAMPLE:
% > name = {'Simon', 'Jimmy', 'Cooper'}';
% > grade = {99, 68, NaN}';
% > vars2cell(name, grade)
% ans = 
%     'name'      'grade'
%     'Simon'       [   99]
%     'Jimmy'     [   68]
%     'Cooper'    [  NaN]
%     
% > vars2cell(name, grade,{'NAME','GRADE'})
% ans = 
%     'NAME'      'GRADE'
%     'Simon'       [   99]
%     'Jimmy'     [   68]
%     'Cooper'    [  NaN]    

%  END OF EXAMPLE
%=============================================
    vl = varargin{nargin};
    if iscellstr(vl) && length(vl) == nargin-1  && length(varargin{1}) ~=1
        nvar = nargin-1;
    else
        nvar = nargin;
    end
    for ii = 1:nvar
        if size(varargin{ii},2) >1
            varargin{ii} = varargin{ii}';
            warning('input should be vector');
        end
        if ii >=2 && size(varargin{ii},1) ~= size(varargin{ii-1},1) 
            error('input should be same obs');
        end
    end

    for ii = 1:nvar
        if iscell(varargin{ii});
            cellA(:,ii) = [{inputname(ii)}; (varargin{ii})];
        else
            cellA(:,ii) = [{inputname(ii)}; num2cell(varargin{ii})];
        end
    end
    
    if nvar == nargin-1
        if size(varargin{nargin},2) ~= nvar 
            error('the no of var in cell and rename list should be the same!');
        end
        cellA(1,:) = varargin{nargin};
    end
    
return;
end

Contact us