尝试:
>> x = sym('x',[1 2])
x =
[ x1, x2]
>> x(1)
ans =
x1
>> x(2)
ans =
x2
>> whos x
Name Size Bytes Class Attributes
x 1x2 112 sym
这类似于写作:
>> syms a1 a2
>> a = [a1 a2]
编辑:
首先,我们从符号变量构建一个表达式:
a = sym('a', [1 2]);
x = sym('x', [1 2]);
expr = x(1)/a(1)+x(2)/a(2);
接下来我们将其转换为常规的 MATLAB 函数:
fh = matlabFunction(expr, 'file','test1', 'vars',{a,x});
生成的函数是:
function expr = test1(in1,in2)
a1 = in1(:,1);
a2 = in1(:,2);
x1 = in2(:,1);
x2 = in2(:,2);
expr = x1./a1+x2./a2;
end
最初我正在考虑使用正则表达式来修复生成的函数句柄。这是一个更肮脏的黑客,所以我建议使用以前的方法:
% convert to a function handle as string
fh = matlabFunction(expr);
str = char(fh);
% separate the header from the body of the function handle
T = regexp(char(fh), '@\((.*)\)(.*)', 'tokens', 'once');
[args,body] = deal(T{:});
% extract the name of the unique arguments (without the index number)
args = regexp(args, '(\w+)\d+', 'tokens');
args = unique([args{:}], 'stable');
% convert arguments from: x1 into x(1)
r = sprintf('%s|', args{:}); r = r(1:end-1);
body = regexprep(body, ['(' r ')(\d+)'], '$1($2)');
% build the arguments list of the new function: @(a,b,c)
head = sprintf('%s,', args{:}); head = head(1:end-1);
% put things back together to form a function handle
f = str2func(['@(' head ') ' body])
生成的函数句柄:
>> f
f =
@(a,x)x(1)./a(1)+x(2)./a(2)