Late updating function output in MATLAB - R2015b - matlab

I have the following code; this function is called from a parent script, and produces a GUI that allows the user to select a threshold parameter.
Unfortunately, the output parameter threshold is updated late. For example, the first time the function is run, irrespective of how I use the slider, it reports threshold as being empty, even if I have set thresh_final to 0.9. The next time I run the function, it immediately updates threshold as 0.9, before I can adjust thresh_final. That is, when I run the function at time t, it outputs the value of threshold as the selected value of thresh_final at time t-1.
function threshold = threshold_choose(frames,prob_mat)
global thresh_final
f1 = figure('Visible','on','pos',[100,50,800,800]);
ax1 = axes('Units','Pixels');
work_im = prob_mat(:,:,2);
normali = max(max(work_im));
work_im = work_im ./ normali;
user_choose = work_im > 0.8 ;
demoImage = mat2gray(user_choose);
imshow(demoImage)
sld = uicontrol('Style', 'slider',...
'Min',0,'Max',1,'Value',0.8,...
'Position', [200 50 300 20],...
'Callback', #thresh_change);
function thresh = thresh_change(source,~)
thresh = source.Value;
figure(f1)
user_choose = work_im > thresh ;
demoImage = mat2gray(user_choose);
imshow(demoImage)
thresh_final = thresh;
closeing = uicontrol('Style','pushbutton',...
'String','Close GUI',...
'Position',[700,20,80,80],...
'Callback', #closeAll);
end
function closeAll(~,~)
close all
end
end
threshold = thresh_final;
end
At the moment, to get around this bug, I can simply call the function, adjust the parameter, then close the GUI, and then call the function again, but close the GUI immediately, without adjusting the parameter, but this is not really practical.
I figure that this is because when I call the function, it runs the whole script, including the last line threshold = thresh_final, and then waits to run the nested functions until they are called, but I don't know how to get around this.
Any help would be much appreciated.

Related

Matlab stop function's execution

I have an array. I am processing elements of this array in a for loop inside a function.
function results = processArray(array)
for ii = 1:length(array)
%some stuff here
results(ii) = %getting the results for this particular element
end
end
There might be a lot of elements and computations might take a lot of time. I want to be able to finish execution of the for loop at any arbitrary time when a user wants to do that so that the results for already processed elements would be available.
I was trying to make a figure with a button which would change a boolean flag. Inside the for loop I was checking the value of that boolean. If the boolean changed then the for loop should break.
function results = processArray(array)
fig = figure;
fig.UserData.continue = 1;
uicontrol('Parent', fig', 'Style', 'pushbutton', 'String', 'stop', 'callback', #interrupt)
for ii = 1:length(array)
if(fig.UserData.continue == 0)
break;
end
%some stuff here
results(ii) = %getting the results for this particular element
end
end
function interrupt(obj, ~)
fig = obj.Parent;
fig.UserData.continue = 0;
end
well, that does not work. The figure shows up only after all the computations are done already. If I draw the figure first using something like waitforbuttonpress and proceed to the for loop pressing the button does not stop the execution. I think the callback function is being executed only after the for loop is finished. Is there any way to solve this?
You will need to drawnow after you create the button, so it will show up. You also need to drawnow within the loop to update the button state. Then you should achieve what you want.
drawnow force figure update, so it will slow down your computation a little.

How to update date and time in matlab gui

function demo1()
H.f = figure('Name','DEMO1');
set(H.f,'Units','Pixels','Position',get(0,'ScreenSize'));% adjust figure size as per the screen size
H.pb1 = uicontrol('style','push',...
'units','pixels',...
'position',[400 800 280 30],...
'fontsize',14,...
'string', datestr(now)); % datestr(now) is used to get current date and time
end
how i can get the real time clock in gui
This is not really an easy task to perform and you may want to think about your design. This could be wrapped in a class, but not necessarily. In case you do not want to do this you may be able to modify the underlying Java objects, but that seems to be overworking this. I have instead structured this in a more C-style manner with placing all data in a struct and writing functions taking the struct as an argument. However, since matlab does not support passing memory locations you need to return the struct after modifying it.
I have chosen to use a timer object for this. You need to store the timer object somewhere since it needs to be deleted when you are not using it anymore. Further, I have added some code for using a start function and stop function as well. For the timer object. This for seeing that the object actually gets finished during development phase. This is not needed for the final project. Further, you may want to handle the case where the window is closed. This will cause the current implementation to crash since the timer is independent of the figure and does not stop when the figure is closed. You probably want to call stop_timer on closing the figure. Anyway here is the code:
function test()
h.f = figure('Name','DEMO1');
set(h.f,'Units','Pixels','Position',get(0,'ScreenSize'));% adjust figure size as per the screen size
h.pb1 = uicontrol('style','push',...
'units','pixels',...
'position',[400 800 280 30],...
'fontsize',14,...
'string', datestr(now)); % datestr(now) is used to get current date and time
h = start_clock(h);
pause on;
pause(15);
pause off;
h = stop_clock(h);
end
function obj = start_clock(obj)
%TasksToExecute calls the timer object N times
t = timer('StartDelay', 0, 'Period', 1,... % 'TasksToExecute', inf, ...
'ExecutionMode', 'fixedRate');
t.StartFcn = {#my_callback_fcn, 'My start message'};
t.StopFcn = { #my_callback_fcn, 'My stop message'};
t.TimerFcn = {#set_time, obj};
obj.t = t;
start(obj.t);
end
function obj = stop_clock(obj)
stop(obj.t);
delete(obj.t);
end
function set_time(obj, event, arg)
arg.pb1.String = datestr(now);
end
function my_callback_fcn(obj, event, arg)
txt1 = ' event occurred at ';
txt2 = arg;
event_type = event.Type;
event_time = datestr(event.Data.time);
msg = [event_type txt1 event_time];
disp(msg)
disp(txt2)
end

Matlab gui with pause function

I am using the GUIDE for matlab gui.
The gui built in order to communicate with keithley current measurement device through GPIB.
When using a toggle button for Current measurement while loop, i am using a pause() function inside the while loop for each iteration and a ytranspose on the y array reading results.
function Measure_Callback(hObject, eventdata, handles)
global GPIB1
global filename
global timeStep
disp('Measurement in progress \n stopwatch starts!');
tic
x=0;
n=0;
while get(hObject,'Value')
fprintf(GPIB1, 'printnumber(smua.measure.i(smua.nvbuffer1))');
fprintf(GPIB1, 'printbuffer(1,1,nvbuffer1)');
A = fscanf(GPIB1);
if length(A)<20
x = x+1;
n = n+1;
t(n) = toc ;
y(x) = str2double(A);
plot(t,y,'-bo',...
'LineWidth',2,...
'MarkerEdgeColor','k',...
'MarkerFaceColor',[.49 1 .63],...
'MarkerSize',10);
grid on
hold on
end
title('Current vs Time','FontSize', 15)
xlabel('Time [s]','FontSize', 15)
ylabel('Current [A]','FontSize', 15)
a = timeStep;
pause(a)
end
disp('Measurement terminated');
disp('Elapsed time: ');
elapsedtime = toc;
elapsedtime_string = num2str(elapsedtime);
disp(elapsedtime_string);
ytrans = transpose(y);
csvwrite(filename,ytrans);
fprintf(GPIB1, 'smua.source.output = smua.OUTPUT_OFF');
For the pause function i'm geting error:
?? Error using ==> pause Error while evaluating uicontrol Callback
For the transpose(y) function i'm also getting a error:
its undefined y.
Cant understand why are those errors and could use some help.
Thank you!
First off, as people say, post the errors and the code. Do you know if length(A) is smaller than 20 in the first time you run the loop? Because if not, A is not defined and you can't transpose something that is not there. Initialize A before the loop to something and see if the error persists (or print out length(A) to make sure the loop gets entered the first run).
As for the pause error, make sure pause is an int or double, not a string. If you get your global timeStep from the GUI field, it is probably a string and you need to covert it to double first.

Matlab assignin('base',...) Resets

I am attempting to write a function that, if called before any animation, will handle the close events without extra code in the animation file.
function matlabStopFunction(varargin)
persistent runs
if runs==2
runs = [];
end
if isempty(runs)
evalin('base','figure(''DeleteFcn'',#matlabStopFunction);');
runs = 1;
else
assignin('base','play',false);
pause(1);
runs = 2;
end
end
Here's a sample animation code that I've been using:
function sampleAnimation
matlabStopFunction;
r = 5;
th = 0;
play = true;
while play
x = r * cosd(th);
y = r * -sind(th);
plot(x,y,'r*');
axis([-10 10 -10 10]);
th = th + 45;
pause(0.25);
end
end
The stop function works fine creating the figure, and when I close the figure, it calls the same function as expected (including the assignin on line 10). However, when stepping through, when I first get back to the base function (sampleAnimation), play is false as would be expected:
But when I step one more line, play is reset to true
Am I incorrectly assigning the value of play to false in the stop function, and if so, how could I correct this so that the animation stops when the figure is closed while keeping the code inside the animation to a minimum? I am trying to replicate the method on this blog except with all the code contained in a separate file.
I am running Matlab 2014b on Windows 8.1.
To answer your question - you are modifying the value play in the base workspace - where as the loop is in the workspace of the sampleAnimation function -> so you are not changing the required value to stop the animation. To verify this clear your variables in the base workspace clear before you run your code and you will see that the variable play is created and set to false.
By the way there is a much simpler way to do this, you animation can create a figure and then you can stop when it is deleted:
function sampleAnimation
h = figure;
r = 5;
th = 0;
while ishandle ( h )
x = r * cosd(th);
y = r * -sind(th);
plot(x,y,'r*');
axis([-10 10 -10 10]);
th = th + 45;
pause(0.25);
end
end

using timer in MATLAB to extract the system time

!I am using MATLAB to design an Analog Clock. Currently, my code simply displays the (or plots rather) the clock design with the hands (hours, mins, secs) and does not tick. Here is my code:
function raviClock(h,m,s)
drawClockFace;
%TIMER begins-------
t = timer;
t.ExecutionMode = 'FixedSpacing'; %Use one of the repeating modes
t.Period = 1; %Fire on 1 second intervals
t.TimerFcn = #timer_setup; %When fired, call this function
start(t);
set(gcf,'DeleteFcn',#(~,~)stop(t));
end
function timer_setup(varargin)
format shortg;
timenow = clock;
h = timenow(4);
m = timenow(5);
s = timenow(6);
% hour hand
hours= h + m/60 + s/3600;
hourAngle= 90 - hours*(360/12);
% compute coordinates for pointing end of hour hand and draw it
[xhour, yhour]= polar2xy(0.6, hourAngle);
plot([0 xhour], [0 yhour], 'k-','linewidth',7.4)
% minute hand
mins= m + s/60;
minsAngle= 90 - mins*(360/60);
% compute coordinates for pointing end of minute hand and draw it
[xmins, ymins]= polar2xy(0.75, minsAngle);
plot([0 xmins], [0 ymins], 'r-','linewidth',4)
%second's hand
second = s;
secAngle = 90- second*(360/60);
[xsec, ysec]= polar2xy(0.85, secAngle);
plot([0 xsec], [0 ysec], 'm:','linewidth',2)
%end % while ends
end
%--------------------------------------------------------
function drawClockFace
%close all
axis([-1.2 1.2 -1.2 1.2])
axis square equal
hold on
theta= 0;
for k= 0:59
[xX,yY]= polar2xy(1.05,theta);
plot(xX,yY,'k*')
[x,y]= polar2xy(0.9,theta);
if ( mod(k,5)==0 ) % hour mark
plot(x,y,'<')
else % minute mark
plot(x,y,'r*')
end
theta= theta + 360/60;
end
end
%-----------------------------------------------------------------
function [x, y] = polar2xy(r,theta)
rads= theta*pi/180;
x= r*cos(rads);
y= r*sin(rads);
end
This is simply taking a static data of values for the HOUR, MINUTE and SECOND arguments when i initially call my function. I tried using the following in a while loop but it didn't help much
format shortg
c=clock
clockData = fix(c)
h = clockData(4)
m = clockData(5)
s = clockData(6)
and passing the h, m and s to the respective cuntions. I want to know how I can use the TIMER obkjects and callbacks for extracting the information of [hrs mins secs] so i can compute the respective point co-ordinates in real time as the clock ticks.
I'd do a couple of things here.
First, you probably don't really need to pass the h, m, s inputs, if you are displaying current time. Add this to the top of your function to auto set these variables.
if nargin == 0
[~,~,~,h,m,s] = datevec(now);
end
Then, it is pretty easy to use a time to call this function periodically. Something like this.
t = timer;
t.ExecutionMode = 'FixedSpacing'; %Use one of the repeating modes
t.Period = 1; %Fire on 1 second intervals
t.TimerFcn = #(~,~)raviClock; %When fired, call this function (ignoring 2 inputs)
start(t); %GO!
Use docsearch timer for in depth documentation of the timer objects. But the code above should get you started.
To stop the timer, run
stop(t);
To stop the timer when the window is closed, put the stop command into the window deletion callback:
set(gcf,'DeleteFcn',#(~,~)stop(t)); %NOte: Better to explicitly use a figure number, rather than gcf.