isuru chathuranga
isuru chathuranga

Reputation: 1025

MATLAB Updating a global variable from one function does not get reflected in the other function

I have a function that uses a global variable and I want to change its value from another function. Even though I tried in many ways, the function that uses the value seems not getting updated with the new value of the global variable. Here's the code I'm using.

calculate.m

function calculateTest()

global isStop;
global value;

value=0;
while ~isStop
    pause(1);
    value = value+1
end

end

start.m

function start()

global isStop;
isStop = 0;
calculateTest();
end

stop.m

function stop()

global isStop;
isStop = 1;
end

When I call start() the value starts getting printed. But even if I call stop(), it never stops. It keeps on printing. Do you have any idea of what I am missing?

(I have tried while isStop==0 as well. But the result was the same.

Upvotes: 1

Views: 2900

Answers (2)

angainor
angainor

Reputation: 11810

I think what you need is a background thread that would do the calculateTest while leaving you the possibility to run stop from a matlab script/command line. This functionality is not supported by MATLAB in the pure sense. You can sometimes implement similar things using the timer functionality. Essentially, you tell MATLAB to run a function repeatedly after some time has passed. However, MATLAB is running the timer function in the foreground. And while it is doing that you can not run your stop script. So you can not implement a long loop in the timer function. timer is only good to schedule some tasks to be executed by MATLAB every now and then, but does not implement threading.

You could implement your own background thread using a MEX function. You could then call the MEX function to pass 'start'/'stop' commands to your thread. But the MEX thread would have to do the data processing inside. You can not e.g. call some matlab script to do the job.

Another thing. start and stop are MATLAB functions that manage the timer. Do not use those identifiers as names of your own functions - that is allowed, but considered a bad practice.

Upvotes: 2

Simon Durrant
Simon Durrant

Reputation: 1

You haven't actually called the stop function anywhere in your code, so there is no opportunity for it to update the global variable.

You could, for example, modify calculateTest() by adding a conditional test which calls the stop function when "value" reaches a certain number, such as 5:-

function calculateTest()

global isStop;
global value;

value=0;
while ~isStop
    pause(1);
    value = value+1
    if value == 5
        stop;
    end
end

end

You will find that this stops it perfectly well. If you added the stop command into start instead, after CalculateTest, that will not work because the flow of control never reaches that line - it remains on CalculateTest until that function is terminated.

Upvotes: 0

Related Questions