annotate core/tools/cell2str.m @ 0:e9a9cd732c1e tip

first hg version after svn
author wolffd
date Tue, 10 Feb 2015 15:05:51 +0000
parents
children
rev   line source
wolffd@0 1 %CELL2STR Convert 2-D cell array into evaluable string.
wolffd@0 2 % B = CELL2STR(C) returns a B such that C = EVAL(B), under the
wolffd@0 3 % following contraits:
wolffd@0 4 % - C contains only numeric, logic, string or cell arrays, not
wolffd@0 5 % structs nor objects.
wolffd@0 6 % - NDIMS(C) = 2.
wolffd@0 7 %
wolffd@0 8 % B = CELL2STR(C,N) uses N digits of precision for numeric
wolffd@0 9 % arrays. N defaults to 15.
wolffd@0 10 %
wolffd@0 11 % B = CELL2STR(C,'class') and B = CELL2STR(C,N,'class') also
wolffd@0 12 % include the class string for the numeric arrays
wolffd@0 13 %
wolffd@0 14 % See also MAT2STR, EVAL
wolffd@0 15
wolffd@0 16 % (C) Copyright 2010-2012, All rights reserved.
wolffd@0 17 % Cris Luengo, Uppsala, 12 August 2010.
wolffd@0 18 % 13 July 2012: extended to work with cell arrays.
wolffd@0 19
wolffd@0 20 function str = cell2str(c,n,mode)
wolffd@0 21
wolffd@0 22 if nargin==2
wolffd@0 23 if isnumeric(n)
wolffd@0 24 mode = '';
wolffd@0 25 else
wolffd@0 26 mode = n;
wolffd@0 27 n = 15;
wolffd@0 28 end
wolffd@0 29 elseif nargin==1
wolffd@0 30 mode = '';
wolffd@0 31 n = 15;
wolffd@0 32 end
wolffd@0 33
wolffd@0 34 if ~isnumeric(n) || numel(n)~=1
wolffd@0 35 error('Input argument N should be a scalar.')
wolffd@0 36 end
wolffd@0 37 if ~ischar(mode) || ~any(strcmp(mode,{'','class'}))
wolffd@0 38 error('Mode string can only be ''class''.')
wolffd@0 39 end
wolffd@0 40
wolffd@0 41 if iscell(c)
wolffd@0 42 N = size(c);
wolffd@0 43 if length(N)~=2
wolffd@0 44 error('Cell array must be 2-dimensional.')
wolffd@0 45 end
wolffd@0 46 str = '{';
wolffd@0 47 for ii=1:N(1)
wolffd@0 48 if ii>1
wolffd@0 49 str = [str,';'];
wolffd@0 50 end
wolffd@0 51 for jj=1:N(2)
wolffd@0 52 if jj>1
wolffd@0 53 str = [str,','];
wolffd@0 54 end
wolffd@0 55 str = [str,cell2str(c{ii,jj})];
wolffd@0 56 end
wolffd@0 57 end
wolffd@0 58 str = [str,'}'];
wolffd@0 59 elseif isnumeric(c)
wolffd@0 60 if ~isempty(mode)
wolffd@0 61 str = mat2str(c,n,'class');
wolffd@0 62 else
wolffd@0 63 str = mat2str(c,n);
wolffd@0 64 end
wolffd@0 65 elseif ischar(c) || islogical(c)
wolffd@0 66 str = mat2str(c);
wolffd@0 67 else
wolffd@0 68 error('Illegal array in input.')
wolffd@0 69 end