MATLAB set_param函数在循环中不起作用



我有一个 Matlab GUI 代码,它可以让您在轴上绘制并将坐标传递给 Simulink 中的常量。按住鼠标按钮时,它应该在轴上绘制并发送坐标,如果没有,它应该发送坐标,但不应该绘制。这是代码: `

function figure1_WindowButtonUpFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global bool;
bool=false;
set(handles.figure1,'WindowButtonMotionFcn',@(hObject,eventdata)figure1_WindowButtonMotionFcn(hObject,eventdata,guidata(hObject)));
%set the WindownButtonMotionFcn back in order to make it work again

function figure1_WindowButtonDownFcn(hObject, eventdata, handles)
set(handles.figure1,'WindowButtonMotionFcn',@empty); %change the windowbuttonmotionfcn in order not to let it work
global bool;
bool=true;
global lastX;
global lastY;
x=0;
while bool
coord=get(handles.axes4,'CurrentPoint');
if coord(1)<0.003
coord(1)=0.003
x=0;
end
if coord(1)>1
coord(1)=1
x=0;
end
if coord(3)<0
coord(3)=0
x=0;
end
if coord(3)>0.95
coord(3)=0.95
x=0;
end
if x>1
arrayX=[lastX coord(1)];
arrayY=[lastY coord(3)];
line(arrayX,arrayY);
set_param('dosya_yukle_deneme/Constant','value',num2str(coord(1)));
end
x=x+1;
lastX=coord(1);
lastY=coord(3);
drawnow;
end
function empty(~,~,~)
% --- Executes on mouse motion over figure - except title and menu.
function figure1_WindowButtonMotionFcn(hObject, eventdata, handles)
coord=get(handles.axes4,'CurrentPoint');
set_param('dosya_yukle_deneme/Constant','value',num2str(coord(1))); 

按下鼠标按钮时,它会绘制线条,但set_param功能不起作用。但是,figure1_WindowButtonMotionFcn中的那个在需要时运行良好。似乎问题出在 while 循环中。任何帮助将不胜感激。

您无法在figure1_WindowButtonDownFcn回调中运行while循环,因为 Matlab GUI 是单线程的。这意味着while循环会阻塞 Matlab GUI 并阻止内容正确更新。您需要让回调返回,以便 Matlab 能够更新 GUI。这是 Matlab 中 GUI 回调的一般规则;您在回调中执行的任何操作都将阻止 GUI。

事实上,你根本不需要while循环,因为每次光标更改时WindowButtonMotionFcn都会回调。将循环中的代码放入figure1_WindowButtonMotionFcn回调中。您还需要一个额外的全局标志,指示按钮是否关闭,但这很容易创建。figure1_WindowButtonDownFcn应设置按钮关闭标志,figure1_WindowButtonUpFcn重置按钮关闭标志。然后figure1_WindowButtonMotionFcn检查是否设置了按钮关闭标志,如果是,则在while循环中执行代码。

我解决了问题!所以我发现代码从一开始就在工作。我已将常量连接到显示器,当figure1_WindowButtonMotionFcn工作时,它显示了该值,但在另一个显示器工作时没有。这似乎是 MATLAB UI 中的一个错误;检测到鼠标按钮时,显示器不会自行更新。

最新更新