-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmfun.m
225 lines (206 loc) · 7.78 KB
/
mfun.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
function g = mfun(f,varargin)
% adapted from matlabFunction, follows the same syntax, but supports
% sparsity
%matlabFunction Generate a MATLAB file or anonymous function from a sym
% G = matlabFunction(F) generates a MATLAB anonymous function from sym object
% F. The free variables of F become the inputs for the resulting function
% handle G. For example, if x is the free variable of F then G(z) computes in
% MATLAB what subs(F,x,z) computes in the symbolic engine. The function handle
% G can be used by functions in MATLAB like FZERO or by functions in other
% toolboxes. The order of the inputs of G matches the order returned by
% symvar(F).
%
% G = matlabFunction(...,PARAM1,VALUE1,...) uses the specified parameter/value
% pairs to customize the generated function. The parameters modify the
% declaration that appears in the generated code. The template for the
% generated code is
% function [OUT] = NAME(IN1,IN2)
% The parameter names can be any of the following
%
% 'file': The value, FILE, must be a string with a valid MATLAB function
% name. If FILE does not end in '.m' it will be appended. If the
% file already exists it will be overwritten. A function handle to
% the function will be returned in G. If the file name parameter is
% empty an anonymous function is generated. The NAME in the function
% template is the file name in FILE.
%
% 'vars': The value, IN, must be either
% 1) a cell array of M strings or sym arrays, or
% 2) a vector of M symbolic variables.
% IN specifies the input variable names and their order IN1,
% IN2,... INM in the function template. If INj is a sym array then
% the name used in the function template is 'inj'. The variables
% listed in IN must be a superset of the free variables in all the
% Fk. The default value for IN is the union of the free variables in
% all the Fk.
%
% Note: not all MuPAD expressions can be converted to a MATLAB function.
% For example piecewise expressions and sets will not be converted.
narginchk(1,inf);
% process inputs
funs = sym(f);
args = varargin(1:end);
opts = getOptions(args);
% compute non-trivial defaults and verify inputs
funvars = getFunVars(funs);
vars = checkVars(funvars,opts);
inputs = getInputs(vars);
varnames = format(inputs);
% generate anonymous function or file
if ~isempty(opts.file)
file = normalize(opts.file,'.m');
% body = renameFileInputs(vars,inputs,funvars);
body = '';
for k = 1:length(inputs)
for j = 1:length(vars{k});
body = [body char(vars{k}(j)) '= in' num2str(k) '(' num2str(j) ');\n'];
end
end
clear(char(file)); % necessary to avoid problems in for-loops
g = writeMATLAB(funs,file,varnames,body);
tmp = exist(char(file),'file'); %#ok
% necessary to make the function available
% on the PATH right away
end
% compute the default value for 'vars'.
% returns the sorted union of the symvars of the funs
function funvars = getFunVars(f)
vars = symvar(f);
vars = unique(vars);
funparams = argnames(f);
funvars = unique([funparams, vars], 'stable');
% get the 'vars' value and check it for errors
function v = checkVars(funvars,opts)
if isempty(opts.vars)
v = funvars;
else
v = opts.vars;
end
[v,vexpanded] = var2cell(v);
if ~isempty(vexpanded)
if ~iscellstr(vexpanded)
error(message('symbolic:sym:matlabFunction:InvalidVars'));
elseif ~all(cellfun(@(x)isvarname(x),vexpanded))
error(message('symbolic:sym:matlabFunction:InvalidVarName'));
end
end
checkVarsSubset(vexpanded,funvars);
% check that the funvars are a subset of the expanded vars.
function checkVarsSubset(vexpanded,funvars)
vars = var2cell(funvars);
missing = cellfun(@(x)~any(strcmp(char(x),vexpanded)),vars);
if any(missing)
misvars = vars(missing);
varnames = format(misvars);
if length(misvars) > 1
error(message('symbolic:sym:matlabFunction:FreeVariables', varnames));
end
error(message('symbolic:sym:matlabFunction:FreeVariable', varnames));
end
% convert a string or sym array into a 1-by-N cell array of strings
% also optionally return the cellstr of expanded sym array vars joined together
function [v,vexpand] = var2cell(v)
if isa(v,'sym')
v = privsubsref(v,':');
v = num2cell(v.');
v = cellfun(@(x)char(x),v,'UniformOutput',false);
elseif ischar(v)
v = {v};
end
if nargout > 1
vexpand = cellfun(@var2cell,v,'UniformOutput',false);
vexpand = [vexpand{:}];
end
function inputs = getInputs(v)
inputs = cell(size(v));
for k = 1:length(v)
inputs{k} = sprintf('in%d',k);
end
% file = normalizeFile(file,ext) append extension ext if file doesn't
% have one already.
function file = normalize(file,ext)
[~,~,x] = fileparts(file);
if isempty(x)
file = [file ext];
end
% Horzcat sym array or cell array v with commas
function varnames = format(v)
if isempty(v)
varnames = '';
else
if ~iscell(v)
v = num2cell(v);
end
varnames = cellfun(@(x)[char(x) ','],v,'UniformOutput',false);
varnames = [varnames{:}];
varnames(end) = [];
end
% Generate MATLAB. f is the expr to generate. file is file name.
% varnames is the formatted input variables
% outputs is the cell array of output names
% mapping is string with input to variable mapping
function g = writeMATLAB(f,file,varnames,mapping)
[fid,msg] = fopen(file,'wt');
if fid == -1
error(message('symbolic:sym:matlabFunction:FileError', file, msg));
end
tmp = onCleanup(@()fclose(fid));
% [f,tvalues,tnames] = optimize(f);
[~,fname] = fileparts(file);
writeHeader(fid,fname,varnames);
if ~isempty(mapping)
fprintf(fid,mapping);
end
writeOutput(fid,f);
g = str2func(fname);
% write out the function declaration and help
function writeHeader(fid,fname,varnames)
symver = ver('symbolic');
if ~isempty(varnames)
varnames = ['(' varnames ')'];
end
symver = symver(1);
fprintf(fid,'function out = %s%s\n',fname,varnames);
fprintf(fid,'%%%s\n',upper(fname));
fprintf(fid,'%% out = %s%s\n\n',upper(fname),upper(varnames));
fprintf(fid,'%% This function was generated by the Symbolic Math Toolbox version %s.\n',symver.Version);
fprintf(fid,'%% %s\n\n',datestr(now));
% write the assignments to the output variables
function writeOutput(fid,expr)
% expr looks something like
% array(1..1, 1..2, (1,1) = array(1..1, 1..2, (1,1) = sin(t5), (1,2) = cos(t)), (1,2) = cos(t5))
% which is an array of arrays (or scalars). each array element is an output.
% We need to deal the elements of expr to outputs
% Note if length(outputs) == 1 then expr has length 2 to keep indexing the
% same as in the array case. This is ok since we never index expr(2).
fprintf(fid,['out = zeros(' num2str(numel(expr)) ',1);\n']); % initialise with zero values
idx = find(expr); % find nonzero entries
for k = 1:length(idx)
fprintf(fid,['out(' num2str(idx(k)) ') = ' char(expr(idx(k))) ';\n']);
end
fprintf(fid,['out = reshape(out,[' num2str(size(expr)) ']);']);
% validator for variable parameter
function t = isVars(x)
t = iscell(x) || (ischar(x)&&size(x,1)==1) || isa(x,'sym');
% validator for file parameter
function t = isFunc(x)
[~,file] = fileparts(x);
if length(file)>namelengthmax
error('filename is longer than what matlab can handle.')
end
t = isempty(file) || isvarname(file);
% parse inputs and return option structure output
function opts = getOptions(args)
ip = inputParser;
verMAT = ver('MATLAB');
if(str2double(verMAT.Version)>=8.2)
ip.addParameter('vars',{},@isVars);
ip.addParameter('file','',@isFunc);
ip.addParameter('outputs',{},@iscellstr);
else
ip.addParamValue('vars',{},@isVars);
ip.addParamValue('file','',@isFunc);
ip.addParamValue('outputs',{},@iscellstr);
end
ip.parse(args{:});
opts = ip.Results;