Reputation: 3
hi everyone I'm trying to write a program in matlab that does show a rectangle in gui and blink it. the speed of blinking is defined as period = 1/ freq
it is a simple but i dont know why it is not working right.
what is want to do is making that rect appear and disappear as freq specified
here is my code and it doesnt show any error
figure
% the flashing block on frequency
t = timer;
set(t, 'executionMode', 'fixedRate');
freq = 10;
period = 1/freq;
set(t, 'Period', 1/freq);
set(t, 'TimerFcn', 'show');
flash = true;
show = rectangle('Position',[0,0,1,1],'FaceColor','w');
hide = rectangle('Position',[0,0,1,1],'FaceColor','black');
while (true);
% set the background to black
set (gcf, 'Color', [0 0 0] );
% drawing the rect box
n = plot(show);
wait = period;
m = plot(hide);
set(gca,'xcolor',get(gcf,'color'));
set(gca,'ycolor',get(gcf,'color'));
set(gca,'ytick',[]);
set(gca,'xtick',[]);
return
end
i dont know why it is not working. so can someone explain to me
Upvotes: -1
Views: 1844
Reputation: 13945
When you use n = plot(show)
or m = plot(hide)
, you are actually trying to plot the number represented by the handles to the rectangle you created, so it's not showing a rectangle but rather a point.
What you can do is define the position of the rectangles before the loop, and simply call the function rectangle
each time you want to display them. However this is cumbersome as you need to delete each rectangle before displaying the new one.
As noted by @CitizenInsane, a much better way is to assign handles to rectangles before the loop (as you are actually doing) and simply toggle the Visible
property of each back and forth; The result is the same but more efficient and less cumbersome.
Example:
figure
% the flashing block on frequency
t = timer;
set(t, 'executionMode', 'fixedRate');
freq = 10;
period = 1/freq;
set(t, 'Period', 1/freq);
set(t, 'TimerFcn', 'show');
flash = true;
RectPos = [0,0,1,1];
%// Set the visible property to off.
show = rectangle('Position',RectPos,'FaceColor','w','Visible','off');
hide = rectangle('Position',RectPos,'FaceColor','k','Visible','off');
% set the background to black
set (gcf, 'Color', [0 0 0] );
while true;
%// Play with the "Visible" property to show/hide the rectangles.
set(show,'Visible','on')
pause(period)
set(show,'Visible','off')
set(hide,'Visible','on');
drawnow
pause(period)
set(hide,'Visible','off');
set(gca,'xcolor',get(gcf,'color'));
set(gca,'ycolor',get(gcf,'color'));
set(gca,'ytick',[]);
set(gca,'xtick',[]);
end
Hope that helps!
Upvotes: 1