Creating fun structure in a loop
4 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Rik
on 17 Mar 2020
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))
More Answers (0)
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!