www.gusucode.com > mbcdata 工具箱 matlab 源码程序 > mbcdata/@cgfuncmodel/setfunction.m
function [obj, ok, msg] = setfunction(obj, sFunc, InputNames, DoTest) %SETFUNCTION Set a new function string into the model % % [OBJ, OK, MSG] = SETFUNCTION(OBJ, STR) sets a new string as the function % in OBJ. The function is tested and only accepted if it can be correctly % evaluated using vectors. % % [OBJ, OK, MSG] = SETFUNCTION(OBJ, STR, INPUTS) specifies the input names % that should be used for the function. % Copyright 2000-2009 The MathWorks, Inc. and Ford Global Technologies, Inc. % DoTest is a boolean flag that specifies whether to perform tests on the % new function. This is used when loading old objects to prevent existing % functions from being rejected. if nargin<4 DoTest = true; end % First of all, check to see if the new_value is a scalar double. if ~ischar(sFunc) error(message('mbc:cgfuncmodel:InvalidArgument')); end ok = true; msg = ''; if isempty(sFunc) ok = false; msg = 'Unable to parse function string: string is empty.'; return end sFuncV = vectorize(sFunc); if nargin<3 InputNames = symvar(sFuncV); end nInputs = length(InputNames); % Construct anonymous function if nInputs>0 args = mbcListString( InputNames); else args = ''; end try hFuncV = str2func(sprintf('@(%s) %s', args, sFuncV)); catch ok = false; msg = 'Unable to parse function string: function appears to be invalid MATLAB syntax.'; return end % Test the function if DoTest evalIn = (1:10)'; evtest = repmat({evalIn}, 1, nInputs); try evalOut = hFuncV(evtest{:}); catch ok = false; msg = ['Unable to evaluate function. Function strings must use valid MATLAB ', ... 'syntax and be capable of being evaluated using vectors as inputs.']; return end % we must return an nx1 vector if ~isvector(evalOut) || (length(evalOut)~=length(evalIn) || size(evalOut, 2) ~= 1) ok = false; msg = 'Function must return a column vector with the same number of elements as the input vector.'; return end end Units = cell(nInputs+1, 1); Ranges = repmat([0;100], 1, nInputs); % Set data into model object obj.func = sFunc; obj.funcv = hFuncV; obj = setsymbols(obj,InputNames); obj = setunits(obj, Units); obj = setranges(obj, Ranges);