【问题标题】:Using 'callback' and 'updateSystem' to Update Plot in Matlab在 Matlab 中使用“回调”和“更新系统”更新绘图
【发布时间】:2014-11-07 08:11:47
【问题描述】:

我编写了以下代码来绘制水箱中水的高度与时间的关系。

A_t = 16;
[h1, t1] = update_plot(A_t);

f = figure;
h = plot(t1, h1);

b = uicontrol('Parent',f,'Style','slider','Position',[81,54,419,23], 'value',A_t, 'min',14, 'max',17);
bgcolor = f.Color;

set(b,'Callback',@(es,ed) updateSystem(h,update_plot((es.Value))))

更新h(水的高度)和t(时间)向量的函数是:

function [h1, t1] = update_plot(A_t)
t = 0:0.01:100;
h = zeros(1, length(t)); 
h_init = 20;
t_0 = 0;
myeps = 1e-5;
i = 1;
h(1) = h_init;

while h(i) > myeps
    i = i + 1;
    h(i) = (sqrt(h_init) - (0.18/A_t)*sqrt(981/2)*(t(i) - t_0))^2;

h1 = h(1:i);
t1 = t(1:i);
end

参数A_t 是我想使用滑块的变量。
我无法让回调函数工作。
我希望在移动滑块时更新绘图。

【问题讨论】:

  • 欢迎来到 StackOverflow。第一个问题写得很好(+1)。你唯一能记住的就是这样写变量名。您可以使用 `-sign 作为环境来获取“代码模式”。对于您的问题:您是否检查过您的函数对于不同的 A_t 值是否正确?

标签: matlab graphics callback matlab-figure matlab-guide


【解决方案1】:

你可以试试这个:

set(b,'Callback', @slider_callback);

function slider_callback(hObject, callbackdata)
    A_t = num2str(hObject.Value);
    update_plot(A_t);
end

那么您还必须使用cla 清除您的图形,并使用plot 和更新值。

【讨论】:

  • 嗨,我搞定了。但是现在我不确定如何在一个框中显示滑块的值。
  • 另外,是否可以链接文本框和滑块,这样当我在框中输入值时,滑块会移动到该位置并更新绘图?
  • 您需要更改回调函数,以便它们在自己的回调函数中更新其他元素的值。您需要首先使用guihandles 创建句柄结构,以便能够设置这些值。
【解决方案2】:

我让它工作了。修改后的代码和功能如下:

function[f] = update_plot(A_t)
t = 0:0.01:100;
h = zeros(1, length(t)); 
h_init = 20;
t_0 = 0;
myeps = 1e-5;
i = 1;
h(1) = h_init;

while h(i) > myeps
    i = i + 1;
    h(i) = (sqrt(h_init) - (0.18/A_t)*sqrt(981/2)*(t(i) - t_0))^2;

h1 = h(1:i);
t1 = t(1:i);
end
f = plot(t1, h1);
legend('Measured', 'Tuned')
grid on

回调函数为:

function change_plot(objHandle, ~)
slider_value = get(objHandle, 'Value');
new_A_t = slider_value;
update_plot(new_A_t);

主要功能是:

A_t = 15.5;

ff = figure;
axes('Parent',ff, 'units', 'normalized',...
    'position',[0.05 0.15  0.9 0.8])

update_plot(A_t);

b = uicontrol('Parent',ff,'Style','slider',...
    'value',A_t, 'min',14, 'max',17,...
    'units', 'normalized',...
    'position', [0.33 0 0.4 0.1],...
    'SliderStep', [0.001 0.1],...
    'callback', @change_plot);

disp_h = uicontrol('style', 'edit',...
    'units', 'normalized',...
    'position', [0.15 0.05 0.15 0.05]);


bgcolor = ff.Color;

现在我想在我创建的“编辑”框中显示滑块的值,但到目前为止还无法让它工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多