Creating fun structure in a loop

Hi,
as a bloody beginner i cant figure out on how i could write a loop, which should sum up a specific term in a symbolic way.
I need
fun = @(x)x(1)*(1 - exp(-xdata/x(2))) + x(3)*(1 - exp(-xdata/x(4))) + x(5)*(1 - exp(-xdata/x(6))) + x(7)*(1 - exp(-xdata/x(8))) - ydata;
but i want to write a loop, so that the term
x(1)*(1 - exp(-xdata/x(2)))
is added as often as i want.
I need it for thermal calculation for a changeable amount of RC-terms in the Foster model, which is later tranformed into the Cauer model.
My code in general:
prompt = {'Enter the desired amount of RC-Terms'};
dlgtitle = 'RC-Terms';
definput = {''};
opts.Interpreter = 'tex';
answer = inputdlg(prompt,dlgtitle,[1 40],definput,opts);
amount = str2double(answer{1});
x0= 1:1:2*amount; % starting position for fit algorithm
for i=1:2:2*amount
x0(1,i)=0.1;
for k=2:2:2*amount
x0(1,k)=1;
end
end
options = optimoptions(@lsqnonlin,'Algorithm','levenberg-marquardt');
fun= %this is, where the loop should be for a variable amount of Rc terms
x = lsqnonlin(fun,x0,[],[],options);
...

2 个评论

I don't understand the question
I need a function that expands automatically based on the selected number. My default term is
x(1)*exp(-t/x(2))
, physically
R(1)*exp(-t/tau(2))
, which should be concatenated as often as you like depending on the number. The vector x contains different values, speaking always [R1 tau1 R2 tau2 R3 tau3 ...]. Therefore I need for 2 terms:
x(1)*exp(-t/x(2))+x(3)*exp(-t/x(3))
For 3 terms:
x(1)*exp(-t/x(2))+x(3)*exp(-t/x(4))+x(5)*exp(-t/x(6))
and so on.
I hope it is clear now :)

请先登录,再进行评论。

 采纳的回答

You could do it with a loop, but I would prefer a more direct strategy. Depending on the shape of x0 and t, the sum version will automatically determine the number of terms, unlike the loop version.
t=rand(2,1);
amount = 2;
% starting position for fit algorithm
x0=zeros(1,amount*2);x0(1:2:end)=0.1;x0(2:2:end)=1;
options = optimoptions(@lsqnonlin,'Algorithm','levenberg-marquardt');
fun_loop=@(x) 0;%initialize
for k=1:2:(2*amount)
fun_loop=@(x) fun_loop(x) + x(k)*exp(-t/x(k+1));
end
fun_sum=@(x)sum( x(1:2:end).*exp(-t./x(2:2:end)) ,2);
x_fit1 = lsqnonlin(fun_loop,x0,[],[],options);
x_fit2 = lsqnonlin(fun_sum,x0,[],[],options);
%if this value is small (0 or at least <1e-15) the 2 methods are equivalent
clc,max(abs(x_fit1-x_fit2))

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

版本

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by