Summation of function handle in cell array

4 views (last 30 days)
Hi all,
I am trying to write a code that fits multiple function to a specific dataset.
In particular, i have created a cell array where i stored my function handle, like below:
for i=1:le
T_fitted=T_fit(i)*ones(length(intensityMatrixFit),1);
funModel{1,i}=@(r,qFit,T_fitted) r(2*i-1).*exp(-qFit.^2.*r(2*i)).*(1-2*exp(-r(2*le+1)./R.*T_fitted+r(2*le+2)/R)./(1-exp(-r(2*le+1)./R.*T_fitted+r(2*le+2)/R)).^2.*(1-sin(q2Fit.*dMean)./(q2Fit.*dMean)));
end
Now i want to sum all the elements of the cell array (namely funModel) to create a unique function handle to fit to my experimental data (I want to do a global fit) but every solution i have tried Matlab returns me an error. Can you please help me?

Answers (1)

Himanshu
Himanshu on 15 Nov 2023
Hey,
I understand that you are trying to sum all elements of a cell array which contains your function handles to create a unique function handle. You can use the cellfun function for this purpose which is used to apply a function to each cell in a cell array.
Here’s how you could use it:
fsum = @(r,qFit,T_fitted) sum(cellfun(@(F) F(r,qFit,T_fitted), funModel));
‘fsum' is a function handle that takes the inputs r, qFit, and T_fitted, applies each function in funModel to these inputs, and then sums the results. You can then use fsum for your global fit to your experimental data.
Refer to the documentation link to the ‘cellfun’ function for more information:
Hope this helps.

Community Treasure Hunt

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

Start Hunting!