Catching a keyboard keypress in a MATLAB GUI - matlab

I am using matlab and I want to have radio buttons, with some keys mapped to it.
The following code works for displaying radio button and taking values from the user. Can someone help me map keys 1 for Female and 2 for Male.
hgen_radio = uibuttongroup('visible','on','Units','pixels','Position',[1750 1045 170,50],'Title','Gender');
set(hgen_radio,'SelectionChangeFcn',#isMale_Callback);
ugen0 = uicontrol('Style','Radio','String','Male',...
'pos',[10 5 50 25],'parent',hgen_radio,'HandleVisibility','off');
ugen1 = uicontrol('Style','Radio','String','Female',...
'pos',[70 5 70 25],'parent',hgen_radio,'HandleVisibility','off');
set(hgen_radio,'SelectedObject',[]);
Thanks in advance!

In MATLAB, keypresses have to be caught by the figure containing the UICONTROLs, and then passed through. Here's one easy way to do this.
hgen_radio = uibuttongroup('visible','on','Units','Normalized','Position',[.2 .2 .2 .2],'Title','Gender');
set(hgen_radio,'SelectionChangeFcn',#(x,y)disp('Clicked!'));
ugen0 = uicontrol('Style','Radio','String','Male',...
'pos',[10 5 50 25],'parent',hgen_radio,'HandleVisibility','off');
ugen1 = uicontrol('Style','Radio','String','Female',...
'pos',[70 5 70 25],'parent',hgen_radio,'HandleVisibility','off');
set(hgen_radio,'SelectedObject',[]);
set(gcf,'keypressFcn',#(x,y)catchKey(hgen_radio,x,y))
where catchKey.m has something like:
function catchKey(hgen_radio,varargin)
switch varargin{2}.Key
case {'1','2'}
%to do: check if previous value was female, or male...
feval(get(hgen_radio,'SelectionChangeFcn'))
otherwise
%pass other keypresss through
end
See: http://www.mathworks.com/matlabcentral/answers/1450 for another example.
For applications of any complexity, you shouldn't pass handles around like I did above; instead store the values of all the handles in APPDATA using setappdata and getappdata. This significantly clarifies a lot of code. e.g. http://www.mathworks.com/help/matlab/ref/setappdata.html

Related

Is it possible to use callbacks to access a single trajectory in Julia's DifferentialEquations Ensemble Problems?

I am new to Julia and trying to use the Julia package DifferentialEquations to simultaneously solve for several conditions of the same set of coupled ODEs. My system is a model of an experiment and in one of the conditions, I increase the amount of one of the dependent variables at mid-way through the process.
I would like to be able to adjust the condition of this single trajectory, however so far I am only able to adjust all the trajectories at once. Is it possible to access a single one using callbacks? If not, is there a better way to do this?
Here is a simplified example using the lorentz equations for what I want to be doing:
#Differential Equations setup
function lorentz!(du,u,p,t)
a,r,b=p
du[1]= a*(u[2]-u[1])
du[2]=u[1]*(r-u[3])-u[2]
du[3]=u[1]*u[2]-b*u[3];
end
#function to cycle through inital conditions
function prob_func(prob,i,repeat)
remake(prob; u0 = u0_arr[i]);
end
#inputs
t_span=[(0.0,100.0),(0.0,100.0)];
u01=[0.0;1.0;0.0];
u02=[0.0;1.0;0.0];
u0_arr = [u01,u02];
p=[10.,28.,8/3];
#initialising the Ensemble Problem
prob = ODEProblem(lorentz!,u0_arr[1],t_span[1],p);
CombinedProblem = EnsembleProblem(prob,
prob_func = prob_func, #-> (prob),#repeat is a count for how many times the trajectories had been repeated
safetycopy = true # determines whether a safetly deepcopy is called on the prob before the prob_func (sounds best to leave as true for user-given prob_func)
);
#introducing callback
function condition(u,t,repeat)
return 50 .-t
end
function affect!(repeat)
repeat.u[1]=repeat.u[1] +50
end
callback = DifferentialEquations.ContinuousCallback(condition, affect!)
#solving
sim=solve(CombinedProblem,Rosenbrock23(),EnsembleSerial(),trajectories=2,callback=callback);
# Plotting for ease of understanding example
plot(sim[1].t,sim[1][1,:])
plot!(sim[2].t,sim[2][1,:])
I want to produce something like this:
Example_desired_outcome
But this code produces:
Example_current_outcome
Thank you for your help!
You can make that callback dependent on a parameter and make the parameter different between problems. For example:
function f(du,u,p,t)
if p == 0
du[1] = 2u[1]
else
du[1] = -2u[1]
end
du[2] = -u[2]
end
condition(t,u,integrator) = u[2] - 0.5
affect!(integrator) = integrator.prob.p = 1
For more information, check out the FAQ on this topic: https://diffeq.sciml.ai/stable/basics/faq/#Switching-ODE-functions-in-the-middle-of-integration

PyGears reordering bits

I would like to reorder bits before sending it to another module. I would like to make gear that will take 2 inputs pixel and weight and output called reordered should be:
reordered[0] = {pixel[0],weight[0]}
reordered[1] = {pixel[1],weight[1]}
Below is a picture that explains desired gear:
I made the assumption that both pixels and weights are coming as one interface thus I group it. This module should look something like this:
#datagear
def reorder( din: Queue[Tuple['pixel', 'weight']] ) -> Array[Queue[Tuple['pixel.data', 'weight.data']], 3]:
pixel = din.data[0]
weight = din.data[1]
return (
((pixel[0], weight[0]), din.eot),
((pixel[1], weight[1]), din.eot),
((pixel[2], weight[2]), din.eot),
)
Datagear is generally used for handling data and reordering it.
But please have in mind that if Pixel and Weight were two interfaces additional logic would be generated for synchronization of these two interfaces.

Getting the number of function calls of fminsearch for each iteration

options = optimset('Display','iter','MaxIter',3,'OutputFcn',#outfun);
[x,fval,~,output] = fminsearch(#(param) esm6(param,identi),result(k,1:end-1),options);
This code will find the local Minimum of my esm6 function and due to the 'Display' Option it will Output strings like this
Iteration Func-count min f(x) Procedure
0 1 36.9193
1 5 35.9815 initial simplex
2 7 35.4924 contract inside
3 9 35.4924 contract inside
4 11 33.0085 expand
So in the command window, i get the function Count for each Iteration step. The structure output, which is created by fminsearch has only the total amount of func-count in it. Is there a way to receive all the Information, that is outputed in the command window also in the Output-structure?
EDIT:
I think i'm pretty Close to the solution. I wrote this outputfunction:
function stop = outfun(x,optimvalues,state);
stop = false;
if state == 'iter'
history = evalin('base','history');
history = [history; optimvalues.iteration optimvalues.funcCount];
assignin('base','history',history);
end
end
due to http://de.mathworks.com/help/matlab/math/output-functions.html this should work, but in fact, matlab tells me,
??? Reference to non-existent field 'funcCount'.
any idea, why this happens?

Connected components ocr in matlab(image processing)

I am trying to get connected components of an image and then run ocr for each connected component.This is my code-
clc
image=imread('im.png');
image=imcomplement(image);
[imx imy]=size(image);
n1=zeros(imx,imy);
symb=zeros(imx,imy);
lin=zeros(imx,imy);
L = bwlabel(image,8) ;%Calculating connected components
mx=max(max(L));
for i=1:mx
[r,c] = find(L==i);
n1=zeros(imx,imy);
rc = [r c];
[sx sy]=size(rc);
for j=1:sx
x1=rc(j,1);
y1=rc(j,2);
n1(x1,y1)=1;
end
figure,imshow(n1);title('components');
r = ocr(n1,'TextLayout','Word')
n=strtrim(r.Text);
end
This is my input image-
One of the connected components which I get is this-
I get this when I display the components in 4th last line.But in the next line I dont get any result for the ocr of this component.So my question is why am I not getting ocr for this component whereas all other componets give some result in ocr.
If,instead of im.png I use this component as input in my very first line of the code-I get an ocr for this.Why is this happening?
Edit- If I use this component as input,I get the ocr.
I don't know exactly what you want to achieve (it was not very clear from your post). But if what you want is to extract the letters in a chemical formula the below code will do the trick.
I = imread('6oua6.png');
s = regionprops(~I,{'BoundingBox'});
for ii=1:numel(s)
bb = s(ii).BoundingBox;
if bb(4)<30 % enforce a limit to discard non-letters
ocr(I,s(ii).BoundingBox, 'TextLayout', 'Block' )
rectangle('Position',s(ii).BoundingBox+[-1 -1 2 2 ],'Edgecolor','y')
pause
end
end
The ocr will identify the letters correctly (at least from the image you supplied).
Binding them as further will just require you to construct some rules.
enjoy.

Is there a way to change directory in Modelica/Dymola automatically?

I have the following problem:
I have over 20 different models which I want to simulate one after another but I want to change the simulation directory each time.
Right now I'm manually changing directory after each simulation (from ./ModelOne to ./ModelTwo) and I'd like to know if there's a way to change it automatically when I initialize or translate the new model.
Regards
Nev
the best way is to write a script I think:
pathOfSave = {"E:\\work\\modelica\\SimulationResult\\Model1\\","E:\\work\\modelica\\SimulationResult\\Model2\\"};
nbSim = 2;
pathOfMod = { "MyModel.",
"MyModel.};
modelsToSimulate = { ""Model1" ,
"Model2"};
//If equdistant=true: ensure that the same number of data points is written in all result files
//store variables at events is disabled.
experimentSetupOutput(equdistant=false, events=false);
//Keep in the plot memory the last nbSim results
experimentSetupOutput(equdistant=false, events=false);
for i in 1:nbSim loop
//delete the result file if it already exists
Modelica.Utilities.Files.removeFile(pathOfSave + modelsToSimulate[i]);
//translate models
translateModel(pathOfMod[i]+modelsToSimulate[i]);
// simulate
simulateModel(
pathOfMod[i]+modelsToSimulate[i],
method="dassl",
stopTime=186350,
numberOfIntervals=nbOfPoi,
resultFile=pathOfSave + modelsToSimulate[i]);
end for;
You can also put the command cd("mynewpath") in the initial algorithm section, if you want it tobe attached to the model.
model example
Real variable;
protected
parameter String currDir = Modelica.Utilities.System.getWorkDirectory();
initial algorithm
cd("C:\\Users\\xxx\\Documents\\Dymola\\MyModelFolder");
equation
variable = time;
when terminal() then
cd(currDir);
end when;
end example;
In any case you can find all commands of dymola in the manual one under the section "builtin commands".
I hope this helps,
Marco