Daniele Kerberos
Daniele Kerberos

Reputation: 209

How can I update a GUI element from a CPU intensive function?

Here it is my problem, i have GUI and a function (func1) written outside the .m file of my figure. I also have a button on my GUI that when pressed launch func1, now this function is very cpu intensive and could take a lot of time before finsh, this is why i would the function to be able to write something on my GUI (insede a static text for eg.).

My first thought was to make func1 write some info into a text file that the GUI could read, but for that i need some kind o multithread programming oh GUI side, and look like matlab doesn't have nothing like that.

On second place i tried to make func1 to call a update(message) function insede the .m file related to the GUI, but it doesen't worked because update is a subfunction and seems that there is no way to call a subfuction outside the file that contain it.

Can please someone help me with that? sorry for my bad english.

Upvotes: 1

Views: 308

Answers (1)

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

Pass around an object that updates the UI, work with it like a reference.

classdef WindowUpdater < handle
    properties(Access=private)
        textBox;
    end

    methods(Access=public)

        function this = WindowUpdater(textBox)
            this.textBox = textBox;
        end

        function Update(this,st)
            set(this.textBox,'String',st);
            drawnow();
        end        
    end

end

Initialize it with your text uicontrol

h = uicontrol('Style','text');
wu = WindowUpdater( h);

Write you intensive function as:

function foo(arg1,arg2,wu)
     %Do some stuff
     wu.Update('Hello world!');
     %Do some more stuff
     wu.Update('Hello world has finished!');
end

This method has a huge SW advantage:

  • Your code logic is separated from the updates of the GUI : You can replace WindowUpdater with another MyNewUpdater that will write to console line, do nothing, etc..

Upvotes: 2

Related Questions