I have a 3D array of dimensions (rows x cols x 8). For each element in the first two dimensions I have 8 values along the third dimension which I must fit to an equation such as exponential, polynomial etc. I have written code for this function, and I'm currently producing my output by looping over the first two dimensions, as follows:
for i=1:rows
for j=1:cols
outputArray(i,j) = functionHandle(inputArray(i,j,1:8));
end
end
Can I somehow use bsxfun, arrayfun, or some other vectorization method to get rid of the for loops, so that I generate my output using something like this?
outputArray = bsxfun(@functionHandle,inputArray)
Adding the functionHandle
function output = functionHandle(xData,yData)
ft = fittype( 'a*exp(-b*x)+c','independent', 'x','dependent','y' );
opts = fitoptions( 'Method', 'NonlinearLeastSquares' );
opts.Algorithm = 'Trust-Region';
opts.Display = 'Off';
opts.MaxFunEvals = 100;
opts.MaxIter = 100;
opts.Robust = 'LAR';
opts.Lower = [-Inf 0 -Inf];
opts.StartPoint = [0.35 0.05 0.90];
% Fit model to data.
[FitResult,~] = fit(xData,yData,ft,opts);
output = FitResult.a;
end
The answer entirely depends on whether your function is vectorized or not. What you should do is write that function so that it allows R
× C
× 8
input and produces R
× C
× N
output, where N
is the number of fit parameters.
That is, vectorization has to be done within the function; it cannot be done outside. From the outside you can only use the function in a loop. Note that arrayfun
is similar, and has comparable performance, to a for
loop.
Since your function basically uses fit
, it seems you cannot vectorize, because fit
takes one set of inputs at a time and produces the corresponding output.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.