如何在MATLAB中使用动态函数名称?

时间:2018-10-02 06:05:30

标签: matlab for-loop

我正在尝试通过使用 static func getUserListFromServer(completion: @escaping(Bool,[Users]?,String?)->() ){ Alamofire.request(APPURL.getFeedbackUserList, method: .get, parameters: nil, encoding: URLEncoding.queryString, headers: nil).responseJSON { (responseJson) in responseJson.result.ifSuccess { do { // Decode data to object let jsonDecoder = JSONDecoder() let root = try jsonDecoder.decode(Root.self, from: responseJson.data!) if let users = root.users{ completion(true,users,nil) }else{ completion(false,nil,"No users found.") } } catch let err { print(err.localizedDescription) completion(false,nil,err.localizedDescription) } } responseJson.result.ifFailure { completion(false,nil,responseJson.result.error?.localizedDescription) } } } 循环来优化以下程序

for

在此程序中。我有很多公式,可以像t = 0:0.1:100; conc = rand(size(t)); syms x equ_1(x) = 10*x.^2+1; equ_2(x) = 5*x.^3+10*x.^2; equ_3(x) = 5*x.^3+10*x.^2; y_1 = equ_1(conc); y_2 = equ_2(conc); y_3 = equ_3(conc); p_1 = polyfit(t,y_1,1); p_2 = polyfit(t,y_2,1); p_3 = polyfit(t,y_3,1); yfit_1 = p_1(1)*conc+p_1(2); yfit_2 = p_2(1)*conc+p_2(2); yfit_3 = p_2(1)*conc+p_2(2); rms_er_1 = double(sqrt((sum((yfit_1-y_1).^2)./length(yfit_1)))); rms_er_2 = double(sqrt((sum((yfit_2-y_2).^2)./length(yfit_2)))); rms_er_3 = double(sqrt((sum((yfit_3-y_3).^2)./length(yfit_3)))); rms = [rms_er_1 rms_er_2 rms_er_3] 等一样手动编写它们。编写公式后,是否可以使用for循环编写其余程序?

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

是的,有可能。您可以将函数打包在单元格数组中,并在循环访问此单元格数组时将值作为参数提供

t = (0:0.1:100)';   
conc = rand(size(t));

% Packing your function handles in a cell array ( I do not have the 
% symbolic math toolbox, so I used function handles here. In your case you
% have to pack your equations equ_n(x) in between the curly brackets{} )
allfuns = {@(x) 10*x.^2+1, ...
    @(x) 5*x.^3+10*x.^2, ...
    @(x) 5*x.^3+10*x.^2};

% Allocate memory
y = zeros(length(t), length(allfuns));
p = zeros(2,length(allfuns));
yfit = zeros(length(t), length(allfuns));
rms = zeros(1, length(allfuns));

% Loop over all functions the cell, applying your functional chain
for i=1:length(allfuns)
    y(:,i) = allfuns{i}(t);
    p(:,i) = polyfit(t,y(:,i),1);
    yfit(:,i) = p(1,i)*conc+p(2,i);
    rms(:,i) = double(sqrt((sum((yfit(:,i)-y(:,i)).^2)./ ...
        length(yfit(:,i)))));
end

这导致

>> rms

rms =

   1.0e+06 *

    0.0578    2.6999    2.6999

您可以在allfuns中将其扩展为任意数量的方程式。

顺便说一句:您正在将polyfit的一阶多项式拟合到使用二阶和三阶函数计算的值。当然,这会导致高rms的粗略拟合。我不知道您的完整问题看起来如何,但是您可以定义一个数组poly_orders,其中包含allfuns中每个函数的多项式顺序。如果在循环中将这些值作为参数提供给polyfit函数,则拟合将更好地工作。

答案 1 :(得分:0)

您可以尝试cellfun

这里是一个例子。

在.m中定义

function y = your_complex_operation(f,x, t)
y_1 = f(x);
p_1 = polyfit(t,y_1,1);
yfit_1 = p_1(1)*x+p_1(2);
y = double(sqrt((sum((yfit_1-y_1).^2)./length(yfit_1))));
end

然后使用cellfunc

funs{1}=@(x) 10*x.^2+1;
funs{2}=@(x) 5*x.^3+10*x.^2;
funs{3}=@(x) 5*x.^3+10*x.^2;
%as many as you need

t = 0:0.1:100;
conc = rand(size(t));

funs_res = cellfun(@(c) your_complex_operation(c,conc,t),funs);