使用函数 `fit` 时如何指定坐标轴

How to specify axes when using the function `fit`

我有两个轴:一个用于查看图像,另一个用于绘制图表。当我尝试指定要在哪个轴上绘制数据时出现此错误:尝试 plot(handles.axis,curve,x,y).

Error using plot. A numeric or double convertible argument is expected
figure
handles.axis = gca;
x = 1:10;
y = 1:10;
curve = fit(x',y','linearinterp');
plot(curve,x,y) % works fine
plot(handles.axis,curve,x,y) % doesn't work
plot(curve,x,y,'Parent',handles.axis)  % doesn't work

您可以将此示例粘贴到 Matlab 中进行试用。如何更正代码以指定轴?

plot in the curve fitting toolbox is not the same as MATLAB's base plot。尽管有用于指定 sfit 对象的父轴的文档化语法,但似乎没有用于 cfit 对象的语法,在这种情况下,您的 fit 调用将返回该语法.

但是,从文档中我们看到:

plot(cfit) plots the cfit object over the domain of the current axes, if any

因此,如果 current axis is set prior to the plot call it should work as desired. This can be done either by modifying the figure's CurrentAxes property or by calling axes 将轴对象的句柄作为输入。

% Set up GUI
h.f = figure;
h.ax(1) = axes('Parent', h.f, 'Units', 'Normalized', 'Position', [0.07 0.1 0.4 0.85]);
h.ax(2) = axes('Parent', h.f, 'Units', 'Normalized', 'Position', [0.55 0.1 0.4 0.85]);

% Set up curve fit
x = 1:10;
y = 1:10;
curve = fit(x', y', 'linearinterp');  % Returns cfit object

axes(h.ax(2));  % Set right axes as CurrentAxes
% h.f.CurrentAxes = h.ax(2);  % Set right axes as CurrentAxes
plot(curve, x, y);

我将我的回答细化如下:

看起来 plot 中的函数 不喜欢在轴后跟两个向量之后的拟合对象。在这种情况下,我会这样做:

x = 1:10;
y = 1:10;
figure % new figure
ax1 = subplot(2,1,1);
ax2 = subplot(2,1,2);

curve = fit(x',y','linearinterp');
plot(ax1,x,curve(x));
hold on;plot(ax1,x,y,'o') % works fine

plot(ax2,x,curve(x));
hold on;plot(ax2,x,y,'o') % works fine

实际上,诀窍是提供 xcurve(x) 作为两个向量,而不是将整个拟合对象提供给 plot 函数。