What is the fastest way to apply polyfit to a speciffic dimension?
3 次查看(过去 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
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.
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!