Increment a variable by Simulink - matlab

I have a problem in Simulink, I have a variable "k" as constant Block (start Value k =1 ) and i want to increment "k" after each time I click on "the simulation button" untill "k" is 4 then it will be reset to 1 again.
i already try this (see atached Image 1), but in this case k it wil be so long inkremented until the Simulation time is finished (see atached Image 2) and that is not what i want.
enter image description here
enter image description here
i will apreciate any Help many thanks Jay

If you just want to update the value every time you run the simulation, your best option would be to put some code in the InitFcn callback.
This is a (optional) block of code which is run every time the model is initialized. To do this navigate File > Model Properties > Model Properties
Select the Callbacks tab, and then the InitFcn callback on the left. The following code will check if k exists yet in the workspace, and set it if not, and increment it if so. If you put it in the callback, and then set the constant block value to k you should get the behavior you want.
if ~exist('k', 'var')
k = 1;
else
k = k + 1;
end
if k>4
k = 1;
end

Related

GUI wait for user input and do something if time runs out

I am working with a script that takes user input. I want the user to answer on the input within 4 seconds otherwise the code shall do something (right now without using a GUI). What I have done so far is to start a tic and prompt a input testInput = input('Enter the number: '); Meanwhile the prompt is open (waiting for input) I am checking if time has not runed out:
elapsed_time = toc;
if elapsed_time > 4
%do something
end
To the problem:
From what I have learned, there's no way to programmatically terminate a running command in MATLAB, or even let the code do something while the prompt is open. Therefore I can not check if 4 sec has passed before the user inputs something. I've read (here) that this might be possible to solve by using a GUI. I have although no idea how to implement this, since I am totally new.
So, would this be possible with a GUI? Because with the command window it is not.
I would really appreciate to see how something simple like this could look like as a GUI (just something very simple, a window with a input box):
%Start a time ticker
tic;
testInput = input('Enter the number: ');
elapsed_time = toc;
if elapsed_time > 4
%do something
end
Here is a small example of a custom GUI where the user should enter a number before a maximum time is reached. Please read some about callbacks, handles, figure options and uicontrol to better understand it.
Note that you might need to do som more fault handling of the input string (check that number is valid)
function EnterNumber()
% Create figure
inDlg = figure('NumberTitle','off','MenuBar','none','ToolBar','none');
% Create timer, set it to run TimerFcn after 4 s
maxTime = 4;
tH = timer('TimerFcn', {#closeFig inDlg}, 'StartDelay', maxTime);
% Create text and input box for number in figure
uicontrol(inDlg,...
'Style','Text','FontSize',14, ...
'String',sprintf('Please enter a number within %d seconds:', maxTime),...
'Units','Normalized','Position',[0.1 0.6 0.8 0.2]);
editBox = uicontrol(inDlg,...
'Style','Edit','Units','Normalized','Position',[0.1 0.5 0.8 0.2], ...
'FontSize',14,'Callback',#returnEditValue);
% Start timer
start(tH);
% Set focus on the edit box so a number could be entered instantly
uicontrol(editBox)
% Wait for figure to be closed (in any way)
waitfor(inDlg)
fprintf('Moving on ...\n');
% Callback function to save number
function returnEditValue(hObject,~)
% Get the number
number = str2double(get(hObject,'String'));
% Example of how to display the number
fprintf('The entered number is %d\n', number);
% Example of saving the number to workspace
assignin('base','number', number);
% Close figure
close(get(hObject,'Parent'));
% Calback function for timer timeout
function closeFig(~,~,figH)
% If figure exist, close it
if ishandle(figH)
close(figH)
fprintf('Too slow!\n')
end

How do I make a function run again on a key press?

I have a function that displays a graph with some random elements. I want to have it so that when the user presses a certain key the function runs again, redistributing these random elements on the graph. What is the best way to go about doing this?
You can wrap this within a while loop and using ginput. Put your function call within a while loop, use ginput and poll for a keystroke, and while this key is being pushed, keep going. Something like this, assuming that your figure is open after each call to the function:
while true
%// Generate random data
%// Call function
%// Open figure
%// Get a key from the user
[~,~,b] = ginput(1);
%// If you push C or c, then continue
if b == 67 || b == 99
continue;
else %// Else, get out
break;
end
end
You want to set a key press callback for a figure you're using in a script by using the KeyPressFcn like so:
h = figure('KeyPressFcn',#testcallback);
Then place the following in a function testcallback.m file (you can also use a function handle):
function testcallback(hObject,callbackdata)
% Check to make sure key pressed is the escape key
if (strcmp(callbackdata.Key,'escape'))
% Do whatever processing you want
imshow(rand(40));
end
end
When you run the script, a figure will appear. Everytime you press escape, the function will fire:
using the input() function in MATLAB allows you to prompt and ask a user for input. You can use this function to prompt the user to enter a key, when this key is entered, your function can be called and re-run.
Documentation on this can be found on the Mathworks website

MATLAB - identification of every typesetted symbol

I have the following code in MATLAB, where the user has to enter the word "precipitations" letter by letter. After typing one letter, the user has to press Enter and the program checks, whether the typed letter was correct.
Now I would like to change the program, such that the user does not have to press Enter after typing a letter. Is there any operator or function in MATLAB which reacts to every pushed button, so one does not have to press Enter?
disp('Please enter "precipitations" without errors')
target=('precipitations');
n=size(target); n=n(2); % Characters number
for i=1:n;
YourInput(i)=input('','s');
if YourInput(i)==target(i)
disp('OK. Please, input the next symbol')
i=i+1;
else
disp('Error. Please try again.')
break
end
end
As far as I know, there is no built-in MATLAB function to do this. There is however a function getkey on MATLAB File Exchange.
You can download this function and change your code to use
YourInput(i) = getkey();
--
I of course wondered how this can be achieved, and it does the following: They create a new figure with a window size of 0,0 at position (1,1). You'll notice the new figure at the bottom left of the screen.
Then, a callback function KeypressFcn which is executed whenever a key is pressed, is created. The pressed key is saved in the UserData field of the figure, and returned as variable. The interesting parts of the function (and a minimal example) are:
fh = figure(...
'keypressfcn','set(gcbf,''Userdata'',double(get(gcbf,''Currentcharacter''))) ; uiresume ', ...
'position',[0 0 1 1] ...
);
uiwait ;
key = get(fh,'Userdata') ;
delete(fh) ;

How to determine the last time a user interacted with the matlab GUI?

In a Matlab function, I would like to know the last time a user interacted with the Matlab GUI. By matlab GUI, I mean basically, a user typing in the command window, or in the editor.
The algorithm I wish to implement is essentially:
If it's been a while, the function will not grab focus, but operate in the background.
If the user has recently interacted, presumably he/she is interested "right now" in the results, and the function will grab focus.
This is a tough one ! Here is a proposition to do what you want with the command window only, based on this undocumented code and persitent variables.
I used two functions: CW_listen and CW_callback. A call to CW_listen (or CW_listen(true)) starts to listen to the command window, while a call to CW_listen(false) stops listening. While listening is on, any action performed on the command window trigs a call toCW_callback.
Here are the two functions:
function CW_listen(b)
% Default value
if ~exist('b', 'var'), b = true; end
% Get the reference handle to the Command Window text area
jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance;
try
cmdWin = jDesktop.getClient('Command Window');
jTextArea = cmdWin.getComponent(0).getViewport.getComponent(0);
catch
commandwindow;
jTextArea = jDesktop.getMainFrame.getFocusOwner;
end
% Instrument the text area's callback
if b
set(jTextArea,'CaretUpdateCallback',#CW_callback);
else
set(jTextArea,'CaretUpdateCallback',[]);
end
and
function CW_callback(varargin)
% Define a persistent variable
persistent last_call;
if isempty(last_call)
last_call = clock;
else
ts = clock;
Dt = etime(ts, last_call);
% Update the status bar
dt = javaMethod('getInstance', 'com.mathworks.mde.desk.MLDesktop');
if dt.hasMainFrame
dt.setStatusText(['Ellapsed time: ' num2str(Dt) 's']);
end
if Dt>5
fprintf('So long !\n');
last_call = ts;
else
% Do nothing
end
end
I also dislayed the ellapsed time in the status bar, it was useful for developping the code and adds a quite cool feature.
You can replace the time in seconds (here 5s) and the fprintf('So long !\n'); by any action of your choice. Be aware that inserting any kind of display outside of this if statement will result in an infinite display loop ...
For the moment I don't see how one could transpose this to the editor, but if you search in Undocumented Matlab you may find how to do it ;)

How to update workspace variable content for every iteration in matlab?

So I have this code
h = SomeFunction;
h.run
for k = 1:4
data_local = h.data;
data_local = data_local+rand(1)
plot(data_local);
pause(2);
end
which outputs 128x25 matrix every second(with a time gap of 2 secounds)
so for each iteration I want this to update the variable in the work space so i used
assignin('base','data',data_local)
inside the loop.
this seems to work, but the thing is only the last value is being stored (after the loop is completed).
Can anyone tell me how to update the variable in the workspace on each loop?
thanks in advance.
Update
this is where the actual file is EmotivEEG headset toolbox