Why isn't this MATLAB class holding on to its

2019-02-19 21:50发布

There must be something very simple that I'm missing here. I have a MATLAB class which creates a figure containing two push-buttons, each button calls the same function, but the handles for those buttons aren't retained within that function, and I don't know why.

Here's the class, simplified...

classdef Test

    properties
        Figure
        ButtonA
        ButtonB
    end

    methods    
        function app = Test()       
            app.Figure = figure();

            app.ButtonA = uicontrol('Style', 'pushbutton', ...
                'String', 'Button A', ...
                'Position', [10, 10, 100, 20], ...
                'Callback', @app.PressButton);
            app.ButtonB = uicontrol('Style', 'pushbutton', ...
                'String', 'Button B', ...
                'Position', [10, 120, 100, 20], ...
                'Callback', @app.PressButton);
        end

        function PressButton(app, Button, ~)
            Button
            app.ButtonA
            app.ButtonB
        end
    end
end

If I call it it opens the figure, and displays the handle numbers for the buttons:

>> T = Test
T = 
  Test with properties:

     Figure: 8
    ButtonA: 745.000122070313
    ButtonB: 103.002319335938
>> T.ButtonA
ans = 745.000122070313
>> T.ButtonB
ans = 103.002319335938

If I press Button A, the function returns two empty values, as if the properties have not been set:

Button =
          745.000122070313
ans =
     []
ans =
     []

If I press Button B, the function does return the value for button A, but an empty value for button B:

Button =
          103.002319335938
ans =
          745.000122070313
ans =
     []

I'd be very grateful for any suggestions.

1条回答
不美不萌又怎样
2楼-- · 2019-02-19 22:21

You should subclass your class from handle. Check the difference between matlab's value-class and handle-class here.

To do so, change the first line in your code:

 classdef Test < handle
查看更多
登录 后发表回答