Matlab Slider- Display left right arrows and move slider every 1 second - matlab

As the title says I am using the GUIDE toolbox in Matlab and I would firstly like to know how I can display the left/right arrows at either end of the slider?
Also how can I get the slider to automatically move every 1 second?
As far as I understand it I need to first create a timer object and set the execution mode and period as follows:
time = timer;
set(time,'executionMode','fixedRate','period',1);
Now I know I need to set the timerFcn to something like:
set(handles.slider1,'Value',x);
in order to change the position of the slider.
Also I understand I need to increment the x variable first by the slider step which in my case is 0.00520833. For example:
x = x + 0.00520833;
So I have some code as follows:
time = timer;
set(time,'executionMode','fixedRate','period',1);
time.timerFcn = set(handles.slider1,'Value', x = x + 0.00520833);
start(time);
However this doesn't work, and i'm sure it's because of something stupid that I am doing.
Thanks!
EDIT:
Now I can move the slider every second but what I would like to do is run a function of my own every second instead. For example:
time.timerFcn = #slider_increment;
function slider_increment
set(handles.slider1,'Value', get(handles.slider1,'Value') + 0.00520833)
slider = get(handles.slider1,'Value');
set(handles.text4,'String', slider);
I know this is a little messy but I will sort that later. The problem i'm facing is how to declare my own function inside the GUI script created by guide, and allow the function to access the handles to the GUI objects.

First, this
time.timerFcn = set(handles.slider1,'Value', x = x + 0.00520833);
Definitely produces an error...
I think you want something like this:
h = uicontrol;
time = timer;
set(time,'executionMode','fixedRate','period',1);
%Note: set(h,val,get(h,val) + change)
time.timerFcn = #(x,y)set(h,'position', get(h,'position') + 10);
start(time);

Related

How to get some objects to move randomly in a space lets say a grid of [-5,5]

I need to move some objects lets say 50 in a space (i.e a grid of [-5,5]) and making sure that if the grid is divided into 100 portions most of the portions (90% or more) are once visited by any object
constraints :
object should move in random directions in the grid changing their velocities frequently (change speed and direction in each iteration)
I was thinking of bouncing balls ( BUT moving in random directions even if not hit by anything in space, not they way a real ball moves) , if we could leave them into space in different positions with different forces and each time they hit each other (or getting closer to a specific distance ) they move to different directions with different speed and could give us a result near to 90% hit of portions in the grid .
I also need to make sure objects are not getting out of grid ( could make lb and ub limits and get them back in case they try to leave the grid)
My code is different from the idea I have written above ...
ux = 1;
uy = 15;
g = 9.81;
t = 0; x(1) = 0;
y(1) = 0;
tf = 2.0 * uy / g; % time of flight back to the ground
dt = tf / 20; % time increment - taking 20 steps
while t < tf
t = t + dt;
if((uy - 0.5 * g * t) * t >= 0)
x(end + 1) = ux * t;
y(end + 1) = (uy - 0.5 * g * t) * t;
end
end
plot(x,y)
this code makes the ball to go with Newton's law which is not the case
Bottom line i just need to be able to visit many portions of grid in a short time so this is why i want the objects to moves in a chaotic way in the space in a random manner (each time running the code i need different result so it needs to be random path) and to get a better result i could make the objects bounce to different directions if they hit or visit each other in the same portions , this probably give me a better result .

Range Based Slider (Control both Ends)

Hi I'm looking for a clean way to produce a slider in matlab that allows me to adjust both ends of the range. Rather than dragging a single value I would like to be able to control the end points of the slider.
I can accomplish this using two sliders with Matlab but am wondering if there is any way that this can be combined into a single control
Example showing slider that I would like.
http://demos.jquerymobile.com/1.3.0-rc.1/docs/demos/widgets/sliders/rangeslider.html
This can be accomplished through the use of a third party java jar using Swing along with Matlabs handle and javacomponent functions. I've adapted this from the JIDE Common Layer (Open Source)
Apparently Matlab can use standard Swing components. This is discussed on Undocumented Matlab.
You will end up with a slider that looks like so:
Here is the code:
function [hcomponent, hcontainer] = createSlider
% Add the 3rd Party Jar, should use static path but for the example, we
% use dynamic
javaaddpath('C:\PathToJars\jide_demo.jar')
import com.jidesoft.plaf.LookAndFeelFactory;
import com.jidesoft.swing.JideButton;
import com.jidesoft.swing.JideSwingUtilities;
import com.jidesoft.swing.RangeSlider;
import com.jidesoft.swing.SelectAllUtils;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
minField = JTextField();
maxField = JTextField();
SelectAllUtils.install(minField);
SelectAllUtils.install(maxField);
rangeSlider = RangeSlider(-100, 100, -100, 100);
rangeSlider.setPaintTicks(true);
rangeSlider.setPaintLabels(true);
rangeSlider.setPaintTrack(true);
rangeSlider.setRangeDraggable(false);
rangeSlider.setMajorTickSpacing(25);
rangeSlider = handle(rangeSlider, 'CallbackProperties');
function updateValues(~, ~)
minField.setText(num2str(rangeSlider.getLowValue()));
maxField.setText(num2str(rangeSlider.getHighValue()));
end
rangeSlider.StateChangedCallback = #updateValues;
minField.setText(num2str(rangeSlider.getLowValue()));
maxField.setText(num2str(rangeSlider.getHighValue()));
minPanel = JPanel(BorderLayout());
minPanel.add(JLabel('Min'), BorderLayout.BEFORE_FIRST_LINE);
minField.setEditable(false);
minPanel.add(minField);
maxPanel = JPanel(BorderLayout());
maxPanel.add(JLabel('Max', SwingConstants.TRAILING), BorderLayout.BEFORE_FIRST_LINE);
maxField.setEditable(false);
maxPanel.add(maxField);
textFieldPanel = JPanel(GridLayout(1, 3));
textFieldPanel.add(minPanel);
textFieldPanel.add(JPanel());
textFieldPanel.add(maxPanel);
panel = JPanel(BorderLayout());
panel.add(rangeSlider, BorderLayout.CENTER);
panel.add(textFieldPanel, BorderLayout.AFTER_LAST_LINE);
% hcontainer can be used to interact with panel like uicontrol
[hcomponent, hcontainer] = javacomponent(panel, [50, 50, 200, 100], gcf);
end
First you need to create edit boxes on either side of your slider. Assuming that f is the handle for the figure and h is the handle for the slider you can do something like this:
endval1 = uicontrol('Parent',f,'Style','Edit','Position',[180,10,200,23],'String','Your number here', 'Callback', #(src,event)callback(src,event,h));
Of course change the position to what suits your needs and create two of them for top and bottom.
Notice how I have a callback with the following #(src,event)callback(src,event,h). Here I'm passing in the handle for the slider (h) so I can modify it when I need.
Now for the callback:
function callback(src, event, h)
n = num2str(src.String);
set(h, 'Min', n);
end
That's an example of a callback. You will need another for the other end of course. Keep in mind that if your new min value is larger than either the current slider value or max value, it will not render until the remaining two are updated accordingly. The same of course applies to the max value.
Hope this helps.

Drawing a resizeable box on an image

I'm working on a gui and using GUIDE. It loads and image and has the user draw an ROI around a point (the particle ROI). I would then like to have two sliders for creating a second ROI (the Scan ROI) where the user can use sliders to set the width and height of the second roi and see it updated on the image. The sliders seem to work ok but my gui keeps drawing a new roi on top of the image so it gets messy looking really fast. I would like to remove the user sizeable roi from the image before redrawing it (while still keeping the original particle ROI on the image. I currently do it the following way :
Inside the callback for the setroi size button (this should be for the particel ROI)
handles=guidata(hObject);
particleroiSize=imrect;% - draw a rectagle around the particle to get a meausr eof ROI size
roiPoints=getPosition(particleroiSize); %-get tha parameters fo the rectanlge
partX1 = round(roiPoints(1));
partY1 = round(roiPoints(2));
partX2 = round(partX1 + roiPoints(3));
partY2 = round(partY1 + roiPoints(4)); % these are the ROi positions in pixels
roiHeight = round(roiPoints(3)); % - these are just the ROI width and height
roiWidth = round(roiPoints(4));
handles=guidata(hObject); %_ update all the handles...
handles.partX1=partX1;
handles.partX2=partX2;
handles.partY1=partY1;
handles.partY2=partY2;
handles.roicenterX = (partX1 + round(roiPoints(3))/2);
handles.roicenterY= (partY1 + round(roiPoints(4))/2);
handles.roiHeight = roiHeight;
handles.roiWidth = roiWidth;
current_slice = round(get(handles.Image_Slider,'Value'));
particleImage=handles.Image_Sequence_Data(partY1:partY2,partX1:partX2,current_slice);
handles.particleImage=particleImage;
set(handles.RoiSizeDisplay,'String',strcat('Particle ROI is ',' ',num2str(roiHeight),' ', ' by ',num2str(roiWidth)) );
guidata(hObject,handles);
And then inside the call back for the sliders that set the Scan ROI size I have (this is inside two different sliders one adjusts the width and one the height :
handles=guidata(hObject);
try
delete(handles.ScanArea);
% plus any cleanup code you want
catch
end
WidthValue = get(handles.ScanAreaSliderWidth,'value');
HeightValue = get(handles.ScanAreaSliderHeight,'value');
set(handles.ScanAreaWidthDisplay,'String',strcat('Scan Area Width is ',' ', num2str(WidthValue))); % sets the display..now to do the drawing...
%h = imrect(hparent, position);
%position = [Xmin Ymin Width Heigth];
position = [ round(handles.roicenterX-WidthValue/2) round(handles.roicenterY-HeightValue/2) WidthValue HeightValue];
handles.ScanArea = imrect(handles.Image_Sequence_Plot,position);
%h = imrect(hparent, position)
handles=guidata(hObject);
guidata(hObject, handles);
But it never deletes the scan area ROI and keeps redrawign over it..I thought the try...catch would work but it doens't seem to. Am I making extra copies of the ROI or something? Please help..
Thanks.
If you need to delete the ROI drawn with imrect, you can use findobj to look for rectangle objects (which are of type "hggroup") and delete them:
hfindROI = findobj(gca,'Type','hggroup');
delete(hfindROI)
and that should do it. Since you first draw particleroiSize, which is of the hggroup type as well, you might not want to delete all the outputs from the call to findobj. If there are multiple rectangles in your current axis, then hfindROI will contain multiple entries. As such you might want to delete all of them but the first one, which corresponds to particleroiSize.
I hope i got your question right. If not please ask for clarifications!
Thanks. This worked perfectly except that I had to use
hfindROI = findobj(handles.Image_Sequence_Plot,'Type','hggroup');
delete(hfindROI(1:end-1))
to get rid of everything but the first ROI, so I guessteh hggoup objects are added at the start ? (I thought I would use deleted(hfindROI(2:end)) to delete all but the first. Also, why does hfindROI return a list of numbers? Do they represent the hggroup objects or something like that?
thanks..

How to get waitbar on top of other figures?

Hi i am using waitbar in a script readAndInitDatabase() which as the name implies reads and initializes image database for further processing.
The problem is this i have used imshow() in this function that is used for displaying the image which is being read, this cause the waitbar to hide behind the figure how can i cause not to let this happen?
I have tried to use set command to set the position of the bar at every iteration but this completely changes the size which i don't want. This is the code for setting the position
parentFolder = ['E:\' ...
'Hand-Gesture\Project\Project_0\' ...
'Images\Database'];
parentFolder = strcat(parentFolder(1:end));
chars = 'abcdefghijklmnopqrstuvwxyz';
h = waitbar(0,'Reading Database Images');
for i = 1:length(chars)
letter = chars(i);
folder = strcat(parentFolder,'\',letter);
read_folder(folder);
waitbar(i/length(chars));
% this code sets the position of waitbar at every iteration
screenSize = get(0,'ScreenSize');
pointsPerPixel = 72/get(0,'ScreenPixelsPerInch');
width = 360 * pointsPerPixel;
height = 75 * pointsPerPixel;
pos = [screenSize(3)/2-width/2 screenSize(4)/2-height/2 width height];
set(h,'Position',pos);
end
close(h);
How do i do this? I want to avoid the set() command if i can, to do this task.
Try
h = waitbar(0,'Reading Database Images','WindowStyle','modal');
Setting the figure property window style to 'modal' keeps the figure in the foreground and eliminates the menu bar (which is already absent in the waitbar anyway).

Adding a slider removes the toolbar

I am facing a strange behavior on Matlab. I want to plot a simple surface in 3D with a variable parameter.
Simple example :
param = 0.5;
[x,y]=meshgrid(linspace(-1,1,10),linspace(-1,1,10));
z = param*x./y;
surf(x,y,z);
I get a classic 3D picture : http://i.imgur.com/2KrnWeH.png
I am now trying to add a slider on my figure to directly control the value of parameter :
function test()
figHandle=figure;
param = 0.5;
[x,y]=meshgrid(linspace(-1,1,10),linspace(-1,1,10));
z = param*x./y;
surfacePlotted = surf(x,y,z);
sliderPosition=[10 400 200 20];
hsl = uicontrol('Style','slider','Min',-2,'Max',2,'SliderStep',[1 1]./(10),'Value',param,'Position',sliderPosition,'Callback',{#updatePlot,surfacePlotted});
end
function updatePlot(hObject,~,eventdata)
surfacePlotted=eventdata;
param = get(hObject,'Value');
x=get(surfacePlotted,'XData');
y=get(surfacePlotted,'YData');
z = param*x./y;
set(surfacePlotted,'ZData',z);
end
I get a nice slider, and I can click on it to modify the parameter : http://i.imgur.com/TqkMSmH.png
i.imgur.com/i9xablF.png (second picture with an other position for the slide
However the main menu bar is not here anymore, especially the "Pan" icon which allow me to manipulate in 3D the figure.
I tried to add it manually after my slider definition
uicontrol('MenuBar','figure');
and I also tried :
set(figHandle, 'MenuBar', 'figure');
without success so far.
Anyone already encoutered this issue and found a work around ? Or Am I simply missing something easy ?
Thanks :)
Edit : Edited picture links, I put the one to manage them
It is addressed here in Yair's website (undocumentedmatlab):
uicontrol side-effect: removing figure toolbar
You only need to add this line into your code:
set(figHandle,'toolbar','figure');