0

I am an engineering student, fairly new to MATLAB. I have created a GUI for a class that calculates voltages and amperages of a specified circuit. I wish to display the amperages as (A) and (mA). The program currently calculates the data and displays it in static text boxes. I am using a button group with two radio buttons inside, working exclusively. I have used selectionChangeFcn in the following manner to control the buttons.

function group_SelectionChangeFcn(hObject, eventdata, handles)

switch get(eventdata.NewValue,'Tag') % Get Tag of selected object.
    case 'radiobutton1'
        var=1;
        set(handles.text1, 'String', '(A)');
    case 'radiobutton2'
        var=1000;
        set(handles.text1, 'String', '(mA)');
    otherwise     
end

Choosing one button or the other changes text in the static text boxes, and assigns a value to a variable. The bulk of the programming code is executed under a pushbutton. All of the variables are contained in this code, and are filled from edit boxes. Everything else works great so far. Within the cases I have (A) or (mA) outputted to a static text box, and you can see that operating the buttons does in fact display different values. My problem is this; I wish to use variable var in the code to multiply my answer data so that it reads in either A or mA. Like this;

set (handles.text36,'string',num2str(ir1*var,'%20.3f'))

I cannot get this to work, however, the error says that var is undefined. It seems to do this in all circumstances. I have experimented with moving the code to different locations, but I cannot get it to work. Any help or ideas would be appreciated.

4

3 回答 3

0

基于您的 set 行与其他方法不在同一个函数中的想法,您必须将 var 全局定义,通过函数调用发送,或保存到句柄或其他对象。这是一种保存可以从任何函数访问的数据的方法。

首先,将主 gui 的句柄保存到根地址。在程序的 Main_OpeningFcn 中调用它。

setappdata(0, ‘mainGUI’, gcf);

然后,在您的代码调用中

mainGUI = getappdata(0, ‘mainGUI’);
var = someValue;
setappdata(mainGUI, ‘var’, var);

这将 var 变量保存在 mainGUI 中。现在你可以通过调用 getappdata 从任何你想要的地方访问 var。您确实必须先获取 mainGUI,但这只是一行。Doug Hull 在 MatLabCentral 上有一段视频。稍后我可以为您找到更详细讨论此问题的链接。这种方法的一个好处是,如果您不需要它,您不必一直传递句柄结构。

于 2013-11-13T03:26:08.263 回答
0

您可能会从阅读这些文章中受益:

http://www.mathworks.de/de/help/matlab/matlab_prog/base-and-function-workspaces.html http://www.mathworks.de/de/help/matlab/creating_guis/ways-to-manage -data-in-a-guide-gui.html#f5-998711

您必须将其存储var在可以从其他 gui 功能访问的地方。

一个例子:在您的第一个函数中更改和存储var,例如作为句柄结构的一部分:

% set var as a field on handles
handles.var = 1000;
% save the guidata - don't miss this!
guidata(hObject, handles);

在您的第二个函数中,应该使用 var 您现在可以var从句柄结构中获取:

set(handles.text36,'string',num2str(ir1*handles.var,'%20.3f'))
于 2013-11-12T14:46:31.413 回答
0

看起来 var 是在 switch 语句中定义的,因此它的范围就在 switch 内部。您应该在开关之外定义 var 以使其范围对函数开放。

此外,在堆栈溢出中编写代码时,在段落之间有一个换行符并将代码缩进 4 个空格,它将被格式化为代码块,见下文。最后,包括换行符,以便可以轻松确定代码行的位置。

switch (...)
   methods
end
于 2013-11-11T23:43:27.113 回答