What is the fastest way to apply polyfit to a speciffic dimension?
4 views (last 30 days)
Show older comments
Hi,
I'm working with 3D images, and I want to fit a polynomial of degree n (user definable) for each pixel along the 3rd dimension of my image. In my current solution, I reshape each image column with the corresponding values in the 3rd dimension to a 2d matrix and convert it to a cell array. Then I use cellfun to do a polyfit for each cell.
dummy = data(:, j, :);
dummy = num2cell(reshape(dummy, iMax, numZsamples), 2);
[curves] = cellfun(@(x) fitCurve(x, numZsamples) ,dummy, 'UniformOutput',false); %fit curve just calls polyfit and polyval
Is there a better, more efficient way to do this?
Best,
Gebhard
2 Comments
John D'Errico
on 7 Oct 2019
I'd suggest doing it by not using polyfit at all, because repeated calls to polyfit will be highly inefficient. The X vector here will not be changing with each call.
Anyway, beyond even moderately small values of N (perhaps 5 or 6 might be a limit) polyfit will start to return numerical garbage, because of the size of the numbers involved if X is essentially a matrix index.
So the fastest way to solve this is by understanding how to use linear algebra to solve the problem, because then you can solve all the fits in one call to backslash. Of course, then you will also understand how to recognize when a polynomial fit has become degenerate, and even how to use centering and scaling to resolve SOME of that problem.
Answers (0)
See Also
Categories
Find more on Interpolation 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!