www.gusucode.com > mbctools 工具箱 matlab 源码程序 > mbctools/validmlname.m
function [validname, OK] = validmlname(name, prefix) % VALIDMLNAME valid MATLAB variable name % % [VALIDNAME, OK] = VALIDMLNAME(NAME, DEFAULT_PREFIX) % % This function takes a single string or a cell array of strings and % checks each for consistency with MATLAB variable names. If the name does % not conflict with MATLAB OK returns true, else OK is false. VALIDNAME % will be a modified version of NAME which does not conflict with MATLAB. % The DEFAULT_PREFIX ('m_' by default) will be appended to names which, % when modified, do not start with a letter. % Copyright 2000-2006 The MathWorks, Inc. and Ford Global Technologies, Inc. % Default prefix if nargin < 2 prefix = 'm_'; end % Deblank the name name = deblank(name); % Have we been given a character array or cell array IS_CHAR = ischar(name); % Convert to a cell array if IS_CHAR name = {name}; end OK = true(size(name)); validname = cell(size(name)); for i = 1:numel(name) vname = name{i}; % First check the validity using the fast builtin isvarname if ~isvarname(vname) OK(i) = false; % Modify the string to make it valid. % (1) Convert to a single row of chars. vname = vname(:)'; % (2) Remove or alter invalid characters if ~isempty(vname) vname(isspace(vname)) = '_'; vname = regexprep(vname, '\W', ''); end % (3) Check the length of the string if numel(vname)>namelengthmax vname = vname(1:namelengthmax); end % (4) Check whether a prefix is required if ~isvarname(vname) vname = [prefix vname]; if numel(vname)>namelengthmax vname = vname(1:namelengthmax); end end end validname{i} = vname; end if IS_CHAR validname = validname{1}; end