simulink run with gui matlab - matlab

i have a Gui and a Simulink Model, i wanna enter some value into the textfield in the Gui and press start Button and after this, my simulink model should take these values and run, the result should be displayed in the gui statictext.
to simulink: i have to constant blocks, thes name ist kraft and flaeche. and the oarameter into the blocks are k and f.
ok now i want to edit the values of k and f in the gui. This is my code:
function kraft_Callback(hObject, eventdata, handles)
kraft_value = str2num(get(hObject,'String'));
if (isempty(kraft_value))
set(hObject,'String','0')
end
guidata(hObject, handles);
function flaeche_Callback(hObject, eventdata, handles)
flaeche_value = str2num(get(hObject,'String'));
if (isempty(flaeche_value))
set(hObject,'String','0')
end
guidata(hObject, handles);
function start_Callback(hObject, eventdata, handles)
k= str2double(get(hObject,'string'));
f= str2double(get(hObject,'string'));
sim('Steifigkeit');
function static_CreateFcn(hObject, eventdata, handles)
But i get these Errors :
Error using Gui>start_Callback (line 215)
Error due to multiple causes.
Error in gui_mainfcn (line 96)
feval(varargin{:});
Error in Gui (line 17)
gui_mainfcn(gui_State, varargin{:});
Error in #(hObject,eventdata)Gui('start_Callback',hObject,eventdata,guidata(hObject))
Caused by:
Error using Gui>start_Callback (line 215)
Error evaluating parameter 'Value' in 'Steifigkeit/f'
Error using Gui>start_Callback (line 215)
Undefined function or variable 'f'.
Error using Gui>start_Callback (line 215)
Error evaluating parameter 'Value' in 'Steifigkeit/k'
Error using Gui>start_Callback (line 215)
Undefined function or variable 'k'.
can somebody help me

I think Simulink is looking for k and f in the base workspace, but they are only defined in your callback function workspace. You probably need to use assignin:
function start_Callback(hObject, eventdata, handles)
k= str2double(get(hObject,'string'));
f= str2double(get(hObject,'string'));
assignin('base','f',f);
assignin('base','k',k);
sim('Steifigkeit');
I don't know how your GUI is constructed, but to me it looks like k and f are the same based on your code. Is this how you meant it to be?

The general form of the command syntax for running a simulation is:
SimOut = sim('model', Parameters)
So this way you can run simulink models from anywhere using commands. you can also add your parameters to the model and run it.
The following example shows how to create a configuration set and use it with the sim syntax.
model = 'vdp';
load_system(model)
simMode = get_param(model, 'SimulationMode');
set_param(model, 'SimulationMode', 'rapid')
cs = getActiveConfigSet(model);
model_cs = cs.copy;
set_param(model_cs,'AbsTol','1e-5',...
'SaveState','on','StateSaveName','xoutNew',...
'SaveOutput','on','OutputSaveName','youtNew')
simOut = sim(model, model_cs);
set_param(model, 'SimulationMode', simMode)
so you just need to replace the values from textbox and that would be this...
I usually use this to set a value in simulink:
Control_Gains(1,1)=str2double(get_param([ModelName,'/PID1/PIDx'],'P'));
or:
NewString = ['[',(num2str(KT)),']'];
set_param([ModelName,'/System/Model/Gain'],'Gain',NewString);

I went through your code but there seems to be no function that will update the constant blocks.. I have created a similar GUI to tune inputs at runtime.
Try this approach:
In the callbacks of your editboxes in the GUI, write these commands
valstr=get(hObject,'String');
val=str2double(valstr);
assignin('base','nameofvariableinmatlabworkspace',val);
set_param('constantblockpath','Value','nameofvariableinmatlabworkspace');
Replace nameofvariableinmatlabworkspace with the name of the variable that appears inside the constant blocks whose value should change according to the value entered in the GUI.
Replace constantblockpath with the path to that constant block e.g. mymodel/Constant12
You might want to do some data validation for the editboxes as well, before assigning their values in the matlab workspace variables.

Related

How to use script in MATLAB allowing functions to be declared?

While making GUI I've came into this problem:
Using script (S) in function (A) makes other functions (B,C,D..., which are declared in function (A)) as undeclared while executing script (S), it happens on MATLAB version R2016b, however everything works fine in MATLAB R2015b.
Basically I have a bunch of axes, and axesPushScript.m script, which executes on click.
Inside script i got this line:
autorange_Callback(handles.autorange, eventdata, handles);
Inside my main function I've got this:
function autorange_Callback(hObject, eventdata, handles)
if (hObject.Value==1)
axis(handles.axesSpectra, 'tight');
axesSpectra_ButtonDownFcn(handles.axesSpectra,eventdata,handles);
else axis(handles.axesSpectra, 'manual');
end
get this error message on MATLAB R2016b:
Undefined function or variable 'autorange_Callback'.
Error in axesPushScript (line 44)
autorange_Callback(handles.autorange, eventdata, handles);
Error in SNOM_alpha_4>axesTrace_ButtonDownFcn (line 463)
axesPushScript;
Error in gui_mainfcn (line 95)
feval(varargin{:});
Error in SNOM_alpha_4 (line 42)
gui_mainfcn(gui_State, varargin{:});
Error in
matlab.graphics.internal.figfile.FigFile/read>#(hObject,eventdata)SNOM_alpha_4('axesTrace_ButtonDownFcn',hObject,eventdata,guidata(hObject))
Error while evaluating Axes ButtonDownFcn
Any ideas of how I could fix it?
%---------------------------------------------------------------
EDIT:
adding .rar file with a simple one button example:
https://www.dropbox.com/s/gsgxb9xt1s6hbvp/junk.rar?dl=0

Why am I getting an error for using fprintf in MATLAB?

This is my code.
function typeHere_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to typeHere (see GCBO)
% eventdata structure with the following fields(seeMATLAB.UI.CONTROL.UICONTROL)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles structure with handles and user data (see GUIDATA)
persistent ticStartTime;
global currentUser;
ticStartTime = tic;
out = sprintf('%s',eventdata.Key);
%disp(out)
if isempty(ticStartTime)
time=toc; % use last the tic from the key_pressFcn
else
time = toc(ticStartTime); % use tic that was called within this callback
end
path = ['Database\' currentUser '\keyCapture_gui1\keyTiming0.txt'];
fd = fopen(path,'a+'); %write in a file
fprintf(fd,'%s\n%s',out,time);
fclose(fd);
This code is accepting each keystroke from a keyboard and simultaneously storing it in a text file but when I run the code, sometimes it works, sometimes it gives the following error message.
Error using fprintf
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in gui1>typeHere_KeyPressFcn (line 162)
fprintf(fd,'%s\n%s',out,time);
Error in gui_mainfcn (line 95)
feval(varargin{:});
Error in gui1 (line 42)
gui_mainfcn(gui_State, varargin{:});
Error in
matlab.graphics.internal.figfile.FigFile/read>#(hObject,eventdata)gui1('typeHere_KeyPressFcn',hObject,eventdata,guidata(hObject))
Error while evaluating UIControl KeyPressFcn
Please help me out, I'm stuck!
What you are doing is to open a file on !EVERY! keypress, appeding some text then closing it.
Therefore, when you press a key you shall open a file and close it !BEFORE! the next keypress arrives. Based on hard drive speed (HDD-SSD) it is absolutely possible that typing fires keypress events faster that your file-handling mechanism can handle. In this case you will get a not valid file identifier as the file still in use (by you).
What I could suggest is to open and close the file only once.
You could store on a buttonpress, or on focus lost of the control where the user typing in.

MATLAB GUI Error while using set

why I cant have the output in the edit text?
% --- Executes on button press in f.
function f_Callback(hObject, eventdata, handles)
% hObject handle to f (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
clc
syms t
a=str2double(get(handles.b1,'string'));
b=str2double(get(handles.c1,'string'));
y=eval(get(handles.a1,'string'));
u=a-b;
m=abs(y).^2;
r=int(m,t);
g1=subs(r,t,a);
h=subs(r,t,b);
fh=g1-h;
s=fh./u
set(handles.e,'string',s)';
Command window shows the answer not edit text.The error is:
Error using set
error: mxArray must be double, char, or cell
Error in signalproject2>f_Callback (line 284)
set(handles.e,'string',s)';
Error in gui_mainfcn (line 96)
feval(varargin{:});
Error in signalproject2 (line 42)
gui_mainfcn(gui_State, varargin{:});
Error in #(hObject,eventdata)signalproject2('f_Callback',hObject,eventdata,guidata(hObject))
Error while evaluating uicontrol Callback
Can u please help me with this?
What is the data type of s? Use whos s to find out.
If it's not a double, char, or cell then you won't be able to assign it as a string for your edit box. This is exactly what the error message tells you.
I don't have the symbolic math toolbox so I can't check the code, but I'm guessing s is a symbolic array. If this is the case, see the documentation for char to convert the symbolic array to a string so you can assign it properly.
Could it simply be because there is a ' you don't want at the end of this line:
set(handles.e,'string',s)';
what if you try:
set(handles.e,'string',s);

How to use both functions and scripts

I'm new to MATLAB and haven't got much programming experience, so I'm pretty stuck.
I need to create a file in which I'd have both functions (due to the GUI I have) and a script. I need to use the variables that I declare in the script in callbacks.
My program is an expert system. Firstly I declare rules as structure arrays, then I execute the algorithm. I don't understand how to call my rules which should be in a script-file inside my function-file.
Update:
I do understand that, however I've read lots of stuff and I still can't figure this out. I have file with the rules, which look like that:
rule(1).condition1='First condition';
rule(1).cond1ask=1;
rule(1).condition2='Second condition';
rule(1).cond2ask=1;
rule(1).conclusion='Conclusion';
rule(1).endmarker=1;
and the file contains ±50 such declarations. Then I have a very simple GUI, which is supposed to run an algorithm when I hit the button. The question is: how do I combine the file with GUI functions and my algorithm and my file with the rules? How can I call the rules from the GUI file?
Here's the GUI code:
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
global rule
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
a1=rule(1).condition(1);
a1
Then I run the GUI file from my script-file, and though the interface loads okay, when I push the button I get error messages:
Improper index matrix reference.
Error in ES_21112012>pushbutton1_Callback (line 83)
a1=rule(1).condition(1);
Error in gui_mainfcn (line 96)
feval(varargin{:});
Error in ES_21112012 (line 43)
gui_mainfcn(gui_State, varargin{:});
Error in
#(hObject,eventdata)ES_21112012('pushbutton1_Callback',hObject,eventdata,guidata(hObject))
Error while evaluating uicontrol Callback
It sounds like your problem is that you dont have access to your variable 'rule' inside your callback function. It can be tricky to do this sometimes when writing GUIs.
One of the most general ways to achieve global access a variable when using GUIs is to use the setappdata function after you first define the variable. I'm confused by your description of your program, but wherever it is that you first define this 'rule' structure you can add this:
% rule = struct(); % Define your rule struct first
setappdata(0, 'myRules', rule);
You can then retrieve this variable without having to somehow pass it to your callback functions as an argument by calling getappdata:
rule = getappdata(0,'myRules');
Note that this is not the only solution and may not be the best for your program but without fully understanding the logic of your program it's hard to give more specific advice.

Error in matlab, while using set in GUI

I have tried the following code in Matlab:
function pushbutton5_Callback(hObject, eventdata, handles)
global smoothening_level;
global Amp_threshold;
global Min_PeakDistance;
global Mat_wave
global Mat_wave2
global Mat_inten
global pks
Mat_inten2 = smooth(Mat_inten,smoothening_level);
[pks,locs] = findpeaks(Mat_inten2,'minpeakdistance',Min_PeakDistance,'minpeakheight',Amp_threshold)
s = size(pks)
figure(1)
Mat_wave2 = Mat_wave(locs(:));
Mat_inten2loc = Mat_inten(locs(:));
hold all;
plot(Mat_wave,Mat_inten2);
plot(Mat_wave2,pks,'o','MarkerEdgeColor','r');
legend('Ouptut Spectrum','Smoothened Spectrum','Identified Peaks')
axis([350 900 0 max(Mat_inten)]);
xlabel('Wavelength')
ylabel('Intensity')
grid on
title('Plasma Emission Spectrum')
temp(:,1)=Mat_wave2;
temp(:,2)=Mat_inten2loc;
set(handles.uitable8,'Data',num2cell(temp))
However it is giving the following error:
??? Attempt to reference field of non-structure array.
Error in ==> GUI>pushbutton5_Callback at 242
set(handles.uitable8,'Data',num2cell(temp))
Error in ==> gui_mainfcn at 96
feval(varargin{:});
Error in ==> GUI at 50
gui_mainfcn(gui_State, varargin{:});
Error in ==> #(hObject,eventdata)GUI('pushbutton5_Callback',hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback
The error tells you that handles is not of type struct. Hence, you can not access handles.uitables8. Most likely what you want to write is
set(handles,'Data',num2cell(temp))', but that is just a guess without knowing the rest of your code.
Check to make sure that handles.uitable8 exists. The easiest way to do this is to set a breakpoint in your code at line 242. When the code stops in debugger, go to your workspace and open the handles structure.
If you created this gui using GUIDE, then most likely the tag is mislabeled or something similar.