What is the fastest way to apply polyfit to a speciffic dimension?

5 次查看(过去 30 天)
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 个评论
John D'Errico
John D'Errico 2019-10-7
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.
Gebhard Stopper
Gebhard Stopper 2019-10-10
OK, done.
Much faster now! Next time I won't be tempted to take the lazy option.

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by