Matlab--二次多项式曲面拟合
二次多项式曲面公式
总共有6个系数。
绘制曲面图形时,一般给定x和y的取值(一维数组),然后对x和y网格化成二维数组X和Y,将X和Y代入公式,即可得到曲面的数值,最后用surf函数显示。
实例
- 给定一个二次多项式模型,然后成图
- x = 0.1 : 0.1 : 5;
- y = 0.1 : 0.1 : 5;
- [X, Y] = meshgrid(x, y);
- Z = X.^2 + Y.^2 + X.*Y + X + Y + 1;
- surf(x, y, Z);
- colormap hot
- shading interp
- 添加噪声,随机选择 100 个点用于拟合
- rng('default');
- Zn = awgn(Z, 30, 'measured');
- xfit = randi(50, 100, 1) / 10;
- yfit = randi(50, 100, 1) / 10;
- zfit = zeros(100, 1);
- for i = 1 : 100
- zfit(i) = Zn(xfit(i) * 10, yfit(i) * 10);
- end
- surf(x, y, Zfit);
- colormap hot
- shading interp
- scatter3(xfit, yfit, zfit, 50, 'MarkerFaceColor', [0 0 0]);
- 用lsqcurvefit函数拟合:拟合结果精度高
- func = @(var,x) var(1)*x(:,1).^2 + var(2)*x(:,2).^2 + var(3)*x(:,1).*x(:,2) + var(4)*x(:,1) + var(5)*x(:,2) + var(6);
- a = lsqcurvefit(func,ones(1, 6),[xfit, yfit],zfit);
- Zfit = a(1) * X.^2 + a(2) * Y.^2 + a(3) * X.*Y + a(4) * X + a(5) * Y + a(6);
- ya = func(a,[xfit, yfit]);
- surf(x, y, Zfit);
- colormap hot
- shading interp
- hold on
- surf(x, y, Zfit);
- shading interp
- scatter3(xfit, yfit, ya, 50, 'MarkerFaceColor', [0 0 1]);
- hold off
- 完整程序
- clear;clc;
- x = 0.1 : 0.1 : 5;
- y = 0.1 : 0.1 : 5;
- [X, Y] = meshgrid(x, y);
- Z = X.^2 + Y.^2 + X.*Y + X + Y + 1;
- rng('default');
- Zn = awgn(Z, 30, 'measured');
- xfit = randi(50, 100, 1) / 10;
- yfit = randi(50, 100, 1) / 10;
- zfit = zeros(100, 1);
- for i = 1 : 100
- zfit(i) = Zn(xfit(i) * 10, yfit(i) * 10);
- end
- func = @(var,x) var(1)*x(:,1).^2 + var(2)*x(:,2).^2 + var(3)*x(:,1).*x(:,2) + var(4)*x(:,1) + var(5)*x(:,2) + var(6);
- a = lsqcurvefit(func,ones(1, 6),[xfit, yfit],zfit);
- Zfit = a(1) * X.^2 + a(2) * Y.^2 + a(3) * X.*Y + a(4) * X + a(5) * Y + a(6);
- ya = func(a,[xfit, yfit]);
- surf(x, y, Zn);
- shading interp
- freezeColors
- hold on
- surf(x, y, Zfit);
- colormap hot
- shading interp
- scatter3(xfit, yfit, zfit, 50, 'MarkerFaceColor', [0 0 0]);
- scatter3(xfit, yfit, ya, 50, 'MarkerFaceColor', [0 0 1]);
- surf(x, y, Z - Zfit);
- shading interp
- hold off
- legend('Model','Fits','Fit','fit','Error');
- 使用cftool工具拟合
- 附录:freezeColors函数可从https://ww2.mathworks.cn/matlabcentral/fileexchange/7943-freezecolors-unfreezecolors下载
- function freezeColors(varargin)
- % freezeColors Lock colors of plot, enabling multiple colormaps per figure. (v2.3)
- %
- % Problem: There is only one colormap per figure. This function provides
- % an easy solution when plots using different colomaps are desired
- % in the same figure.
- %
- % freezeColors freezes the colors of graphics objects in the current axis so
- % that subsequent changes to the colormap (or caxis) will not change the
- % colors of these objects. freezeColors works on any graphics object
- % with CData in indexed-color mode: surfaces, images, scattergroups,
- % bargroups, patches, etc. It works by converting CData to true-color rgb
- % based on the colormap active at the time freezeColors is called.
- %
- % The original indexed color data is saved, and can be restored using
- % unfreezeColors, making the plot once again subject to the colormap and
- % caxis.
- %
- %
- % Usage:
- % freezeColors applies to all objects in current axis (gca),
- % freezeColors(axh) same, but works on axis axh.
- %
- % Example:
- % subplot(2,1,1); imagesc(X); colormap hot; freezeColors
- % subplot(2,1,2); imagesc(Y); colormap hsv; freezeColors etc...
- %
- % Note: colorbars must also be frozen. Due to Matlab 'improvements' this can
- % no longer be done with freezeColors. Instead, please
- % use the function CBFREEZE by Carlos Adrian Vargas Aguilera
- % that can be downloaded from the MATLAB File Exchange
- % (http://www.mathworks.com/matlabcentral/fileexchange/24371)
- %
- % h=colorbar; cbfreeze(h), or simply cbfreeze(colorbar)
- %
- % For additional examples, see test/test_main.m
- %
- % Side effect on render mode: freezeColors does not work with the painters
- % renderer, because Matlab doesn't support rgb color data in
- % painters mode. If the current renderer is painters, freezeColors
- % changes it to zbuffer. This may have unexpected effects on other aspects
- % of your plots.
- %
- % See also unfreezeColors, freezeColors_pub.html, cbfreeze.
- %
- %
- % John Iversen (iversen@nsi.edu) 3/23/05
- %
- % Changes:
- % JRI (iversen@nsi.edu) 4/19/06 Correctly handles scaled integer cdata
- % JRI 9/1/06 should now handle all objects with cdata: images, surfaces,
- % scatterplots. (v 2.1)
- % JRI 11/11/06 Preserves NaN colors. Hidden option (v 2.2, not uploaded)
- % JRI 3/17/07 Preserve caxis after freezing--maintains colorbar scale (v 2.3)
- % JRI 4/12/07 Check for painters mode as Matlab doesn't support rgb in it.
- % JRI 4/9/08 Fix preserving caxis for objects within hggroups (e.g. contourf)
- % JRI 4/7/10 Change documentation for colorbars
- % Hidden option for NaN colors:
- % Missing data are often represented by NaN in the indexed color
- % data, which renders transparently. This transparency will be preserved
- % when freezing colors. If instead you wish such gaps to be filled with
- % a real color, add 'nancolor',[r g b] to the end of the arguments. E.g.
- % freezeColors('nancolor',[r g b]) or freezeColors(axh,'nancolor',[r g b]),
- % where [r g b] is a color vector. This works on images & pcolor, but not on
- % surfaces.
- % Thanks to Fabiano Busdraghi and Jody Klymak for the suggestions. Bugfixes
- % attributed in the code.
- % Free for all uses, but please retain the following:
- % Original Author:
- % John Iversen, 2005-10
- % john_iversen@post.harvard.edu
- appdatacode = 'JRI__freezeColorsData';
- [h, nancolor] = checkArgs(varargin);
- %gather all children with scaled or indexed CData
- cdatah = getCDataHandles(h);
- %current colormap
- cmap = colormap;
- nColors = size(cmap,1);
- cax = caxis;
- % convert object color indexes into colormap to true-color data using
- % current colormap
- for hh = cdatah',
- g = get(hh);
- %preserve parent axis clim
- parentAx = getParentAxes(hh);
- originalClim = get(parentAx, 'clim');
- % Note: Special handling of patches: For some reason, setting
- % cdata on patches created by bar() yields an error,
- % so instead we'll set facevertexcdata instead for patches.
- if ~strcmp(g.Type,'patch'),
- cdata = g.CData;
- else
- cdata = g.FaceVertexCData;
- end
- %get cdata mapping (most objects (except scattergroup) have it)
- if isfield(g,'CDataMapping'),
- scalemode = g.CDataMapping;
- else
- scalemode = 'scaled';
- end
- %save original indexed data for use with unfreezeColors
- siz = size(cdata);
- setappdata(hh, appdatacode, {cdata scalemode});
- %convert cdata to indexes into colormap
- if strcmp(scalemode,'scaled'),
- %4/19/06 JRI, Accommodate scaled display of integer cdata:
- % in MATLAB, uint * double = uint, so must coerce cdata to double
- % Thanks to O Yamashita for pointing this need out
- idx = ceil( (double(cdata) - cax(1)) / (cax(2)-cax(1)) * nColors);
- else %direct mapping
- idx = cdata;
- %10/8/09 in case direct data is non-int (e.g. image;freezeColors)
- % (Floor mimics how matlab converts data into colormap index.)
- % Thanks to D Armyr for the catch
- idx = floor(idx);
- end
- %clamp to [1, nColors]
- idx(idx<1) = 1;
- idx(idx>nColors) = nColors;
- %handle nans in idx
- nanmask = isnan(idx);
- idx(nanmask)=1; %temporarily replace w/ a valid colormap index
- %make true-color data--using current colormap
- realcolor = zeros(siz);
- for i = 1:3,
- c = cmap(idx,i);
- c = reshape(c,siz);
- c(nanmask) = nancolor(i); %restore Nan (or nancolor if specified)
- realcolor(:,:,i) = c;
- end
- %apply new true-color color data
- %true-color is not supported in painters renderer, so switch out of that
- if strcmp(get(gcf,'renderer'), 'painters'),
- set(gcf,'renderer','zbuffer');
- end
- %replace original CData with true-color data
- if ~strcmp(g.Type,'patch'),
- set(hh,'CData',realcolor);
- else
- set(hh,'faceVertexCData',permute(realcolor,[1 3 2]))
- end
- %restore clim (so colorbar will show correct limits)
- if ~isempty(parentAx),
- set(parentAx,'clim',originalClim)
- end
- end %loop on indexed-color objects
- % ============================================================================ %
- % Local functions
- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
- %% getCDataHandles -- get handles of all descendents with indexed CData
- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
- function hout = getCDataHandles(h)
- % getCDataHandles Find all objects with indexed CData
- %recursively descend object tree, finding objects with indexed CData
- % An exception: don't include children of objects that themselves have CData:
- % for example, scattergroups are non-standard hggroups, with CData. Changing
- % such a group's CData automatically changes the CData of its children,
- % (as well as the children's handles), so there's no need to act on them.
- error(nargchk(1,1,nargin,'struct'))
- hout = [];
- if isempty(h),return;end
- ch = get(h,'children');
- for hh = ch'
- g = get(hh);
- if isfield(g,'CData'), %does object have CData?
- %is it indexed/scaled?
- if ~isempty(g.CData) && isnumeric(g.CData) && size(g.CData,3)==1,
- hout = [hout; hh]; %#ok<AGROW> %yes, add to list
- end
- else %no CData, see if object has any interesting children
- hout = [hout; getCDataHandles(hh)]; %#ok<AGROW>
- end
- end
- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
- %% getParentAxes -- return handle of axes object to which a given object belongs
- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
- function hAx = getParentAxes(h)
- % getParentAxes Return enclosing axes of a given object (could be self)
- error(nargchk(1,1,nargin,'struct'))
- %object itself may be an axis
- if strcmp(get(h,'type'),'axes'),
- hAx = h;
- return
- end
- parent = get(h,'parent');
- if (strcmp(get(parent,'type'), 'axes')),
- hAx = parent;
- else
- hAx = getParentAxes(parent);
- end
- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
- %% checkArgs -- Validate input arguments
- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
- function [h, nancolor] = checkArgs(args)
- % checkArgs Validate input arguments to freezeColors
- nargs = length(args);
- error(nargchk(0,3,nargs,'struct'))
- %grab handle from first argument if we have an odd number of arguments
- if mod(nargs,2),
- h = args{1};
- if ~ishandle(h),
- error('JRI:freezeColors:checkArgs:invalidHandle',...
- 'The first argument must be a valid graphics handle (to an axis)')
- end
- % 4/2010 check if object to be frozen is a colorbar
- if strcmp(get(h,'Tag'),'Colorbar'),
- if ~exist('cbfreeze.m'),
- warning('JRI:freezeColors:checkArgs:cannotFreezeColorbar',...
- ['You seem to be attempting to freeze a colorbar. This no longer'...
- 'works. Please read the help for freezeColors for the solution.'])
- else
- cbfreeze(h);
- return
- end
- end
- args{1} = [];
- nargs = nargs-1;
- else
- h = gca;
- end
- %set nancolor if that option was specified
- nancolor = [nan nan nan];
- if nargs == 2,
- if strcmpi(args{end-1},'nancolor'),
- nancolor = args{end};
- if ~all(size(nancolor)==[1 3]),
- error('JRI:freezeColors:checkArgs:badColorArgument',...
- 'nancolor must be [r g b] vector');
- end
- nancolor(nancolor>1) = 1; nancolor(nancolor<0) = 0;
- else
- error('JRI:freezeColors:checkArgs:unrecognizedOption',...
- 'Unrecognized option (%s). Only ''nancolor'' is valid.',args{end-1})
- end
- end
转载自:https://blog.csdn.net/u012366767/article/details/82703670
Matlab--二次多项式曲面拟合相关推荐
- 【Matlab学习手记】二次多项式曲面拟合
二次多项式曲面公式 总共有6个系数. 绘制曲面图形时,一般给定x和y的取值(一维数组),然后对x和y网格化成二维数组X和Y,将X和Y代入公式,即可得到曲面的数值,最后用surf函数显示. 实例 给定一 ...
- 用Matlab求二次多项式,matlab二次多项式拟合
用matlab做散点的二次曲线拟合_数学_自然科学_专业资料.例 对下面一组数据作二次多项式拟合 xi 0.1 0.2 0.4 0.5 0.6 0.7 0.8 0.9 1 yi 1.978 ..... ...
- matlab二次多项式插值,MATLAB应用——多项式与插值函数
数学建模是用数学方法解决各种实际问题的桥梁,它已经渗透到各个领域,而且发挥出越来越重要的作用.面对自然科学和工程应用中的难题,大部分人无从入手,而个别人却能短时间内给出切实可行的解决方案,其差别往往在 ...
- 【C++】【MATLAB】三元二次多项式拟合求极值点原理+代码
一.需求描述 本人最近需要对多个3维数据进行曲线的拟合,并且找到极大值点. 难点: 1.一组数据有125个点,每个点有3个坐标值(x,y,z),以及一个对应的得分值t.x,y,z范围不限,t的范围是0 ...
- 有限元方法数学理论之分片二次多项式空间逼近理论
在一个月之前我已经对有限元方法数学理论之分片一次多项式空间逼近理论进行了讲解,由于中间有点事情所以对二次多项式情况没有进行解说,下面开始正文. 其实思想跟一次多项式的情况一样,只不过这里在一个小区间上 ...
- matlab三次拟合多项式,matlab三次多项式拟合
暂无评价|0人阅读|0次下载|举报文档 DSC曲线的三次样条拟合与Matlab实现_能源/化工_工程科技_专业资料.DSC曲线拟合与Matlab实现第... 人阅读|次下载 曲线拟合的最小二乘法mat ...
- 肤色检测算法 - 基于二次多项式混合模型的肤色检测
1.二次多项式混合模型 二次多项式混合模型首先有SORIANO提出,此后CHIANG对此进行了改进.改进后的模型由两个R-G平面的二次多项式和一个圆方程构成: 在以上三个方程的基础上,肤色区域可以通过 ...
- ML之LiR2PolyR4PolyR:使用线性回归LiR、二次多项式回归2PolyR、四次多项式回归4PolyR模型在披萨数据集上拟合(train)、价格回归预测(test)
ML之LiR&2PolyR&4PolyR:使用线性回归LiR.二次多项式回归2PolyR.四次多项式回归4PolyR模型在披萨数据集上拟合(train).价格回归预测(test) 目录 ...
- ML之LiR2PolyR:使用线性回归LiR、二次多项式回归2PolyR模型在披萨数据集上拟合(train)、价格回归预测(test)
ML之LiR&2PolyR:使用线性回归LiR.二次多项式回归2PolyR模型在披萨数据集上拟合(train).价格回归预测(test) 目录 输出结果 设计思路 核心代码 输出结果 设计思路 ...
最新文章
- 如何线程安全的使用HashMap
- hbase读写流程及缓存机制
- SpringCloud个人笔记-01-Eureka初体验
- TypeError系列之:TypeError: only size-1 arrays can be converted to Python scalars
- apk源码查看工具_如何查看Linux命令工具的源码?
- 【剑指offer】面试题04:二维数组中的查找(java)
- 在IDEA中设置自己的名字和时间
- IIS Tomcat共享80端口
- zookeeper3.3.6 伪分布式安装
- 热带鱼水族箱屏幕保护程序
- 2004年中国十大暴利行业
- android 中文冒号,Kotlin中双冒号::使用方法
- 可口可乐市场调查失败的原因_经典案例可口可乐一次市场调研失败的教训
- 一个程序员的真实故事上
- Kernel panic - not syncing: IO-APIC + timer doesn‘t work解决办法
- 【echarts】在柱状图上方显示数值
- 苹果电脑MACbook Air快捷键大全
- 纯千兆电口和自适应电口的区别
- TFN F7 光时域反射仪 给您不一样体验
- Android studio新手:实现最新版QQ登陆界面