How to pause a for loop in MATLAB to create snapshots? - matlab

So I'm sunning a code which solves an equation over a given period of time. As one would expect, the solution will change as time evolves so I wanted to create some sort of for loop which has the effect of creating "snapshots", which is to say I intend to pause the output at set intervals.
How might I go about implementing such a function?
I was hoping to implement something which pauses the code at defined intervals and then resumes execution on a button press.

Related

Beckhoff - Ramp that can be interrupted/updated while ramping operation is in progress

I am looking for a way to ramp lights properly. This function block looked like a good candidate :
https://infosys.beckhoff.com/english.php?content=../content/1033/tcplclibbabasic/11640060811.html&id=
Unfortunately, it will ignore any subsequent nEndLevel updates. So while ramp is in progress any new values of nEndLevel
Are ignored where what is usually needed from this type of ramp is to stop the current ramping operation and start a new one as soon as new nEndLevel value is received.
Is there any other ramp function block in the Beckhoff library that can do that ?
I need a ramp that can be interrupted/updated while ramping operation is in progress basically.
I don't think you need another function block...
A rising-edge at bStart starts dimming the light from the actual to the end-level (nEndLevel)
bStart: This input starts the dim-ramp from the actual value to nEndLevel within the time defined as tRampTime. This can be interrupted by bOn, bOff or bToggle at any time.
As I understand it, a rising edge on bStart starts a new ramp.
You could try to detect the change in the value of nEndLevel and generate a rising edge on bStart, which should make it generate a new ramp. For example, using a temporary variable nEndLevel_old that retain the old value for comparison in the next cycle.

Is it possible to stop a Simulink simulation when a certain condition is met?

Assume that you have a Simulink simulation where a certain signal is first positive and after some time t in a given interval, it becomes negative. Your goal is to find the zero-crossing.
A first approach would be to plot the signal over the given interval, save it and calculate the zero-crossing.
When repeating this simulation numerous times for varying parameters, it would be beneficial to be able to stop the simulation after the signal has become negative. Then there is already enough information for the calculation of the zero-crossing in Matlab. How could you do that?
Yes, use the Stop Simulation block with the appropriate logical input to the block:
You can use an if / else block to control the flow in the Simulink model. In the if / else block, you can choose the condition if u > 0, continue as normal if it's true, and use the else-option to bypass the rest of the flow you would otherwise run. For instance jump directly to the scope.
Another ways:
You can use Hit Crossing Block in Simulink to find time at the moment of hitting zero.
Another way - use any Trigger or Resettable system. It detects the zero crossing too. For example: this question at SO.
Of course you can also use User Defined function to detect zero crossing by your hand and do whatever you want with the signal at the same time.
About making a lot of simulations and then stops:
you can use Check Upper Static Bound for automatically stops simulation at the moment when zero will be crossed in nth time. For example:
I set upper bound = 10 for this block and this stops at 10th crossing.
There are a lot of ways to save function values in this points or just array of times but this is an another question :)

Any Tic Toc function in Simulink for embedded blocks

I have a system with some embedded Matlab blocks where I'd like to perform some actions after a certain amount of time, in this case turn on lights and switches in an interface to which I send signals from Simulink.
The problem is that I thought I'd use "tic"-"toc" and "while" in a Matlab function block to perform these actions, say one parameter becoming 1 after 5 seconds, the following parameter becoming 1 after 12 seconds and so on, but I noticed that tic-toc apparently doesn't work in Simulink for embedded functions.
Is there any similar functions that could be used in Simulink for embedded functions or is there any other way to do this?
Edit: I've tried to get the clock's time as well, but it's a growing value. Is there any way to "lock" the time as a parameter when the block's function is executed?
You shouldn't be using absolute time in an embedded system, which is at least one of the reasons why tic-toc and clock from MATLAB don't work with Simulink Coder.
You should create your own counter, which you start and stop when you need to.
This is pretty easy to do using a Unit Delay and Summation block.
If you need to be able to enable and/or reset the counter then use the appropriate block from the Additional Discrete library.

Simulink: How to convert event based signal with zero duration values to a time based signal without losing information

I have a matlab function block (which is not relevant) whose input is his previous output (loop). For example, if in a sample period the output is X, his input in the next sample period will be X, and so on.
This image shows a simplification of my simulation. I initialize the input of my function for the first loop.
The problem is that matlab functions recieves an event based signal from de initialization block in the first sample period (zero-duration), which I must convert to a timed based signal (so I can apply the unit delay that avoids an inifite loop, and allows to generate the next input as explained before). So, when I do so, I lose the information contained in the event-based signal (due to the zero-duration values) and the loop does not work.
If there was a way to intialize the loop in the time-based domain (green part of the image) so, in the first sample time, it is not a zero-duration signal, it would avoid the problem.
Is there any way to do so? Or, a different approach for this problem?
Two approaches come to mind
The initial condition can be set in the Unit Delay block, so it's not clear from your simplified example why you need the specific Initialization block.
You could just use a persistent variable inside the MATLAB Function block to maintain the state from one execution of the block to the next (noting that since it is event driven the block may not get called at every time step, only at each event triggger).

How can I parallelize input and display in MATLAB?

I'm using Psychtoolbox in MATLAB to run a behavioral psychology paradigm. As part of the paradigm, users have to view a visual stimulus and respond to it using some input mechanism. For a keyboard, this works as follows:
show stimulus
poll keyboard for response
if no response detected, loop back to 1
if response detected, break and move on with script
This works fine for a keyboard, as step 2 takes between 1-2 ms. The problem comes when I use an alternate input mechanism; in that case, step 2 takes ~20 ms. (I need this alternate input to run the study, and that should be considered immutable fact.) As the stimulus changes with a very short timespan, this added delay breaks the task.
My current thought is to try to use the parallel processing, such that one thread shows the stimulus, and another thread polls the keyboard. I'm currently using the Parallel Computing Toolbox to do this. The problem I'm having is that I don't know how to direct keyboard input to a "parallelized" thread. Does anyone know (1) whether it's possible to direct keyboard input to a thread / have a thread send a visual signal to a monitor, and if yes, (2) how to do it?
Also, if anyone has any better ideas as to how to approach this problem, I'm all ears.
According to this MATLAB newsgroup thread, it appears that threads can't modify graphics objects. Only the desktop MATLAB client can do that. This means that you can't handle updating of graphics from a thread, and I can confirm this as I tried it and wasn't able to modify figures or even the root object from a thread.
However, I think you may be able to do the main graphics updating in MATLAB while a thread handles polling for your input. Here's a sample function for continuously updating a display until a thread waiting for input from KbCheck is finished running:
function varargout = plot_until_input
obj = createJob(); %# Create a job
task = createTask(obj,#get_input,4,{deviceNumber}); %# Create a task
submit(obj); %# Submit the job
waitForState(task,'running'); %# Wait for the task to start running
%# Initialize your stimulus display here
while ~strcmp(get(task,'State'),'finished') %# Loop while the task is running
%# Update your stimulus display here
end
varargout = get(task,'OutputArguments'); %# Get the outputs from the task
destroy(obj); %# Remove the job from memory
%#---Nested functions below---
function [keyIsDown,secs,keyCode,deltaSecs] = get_input(deviceNumber)
keyIsDown = false;
while ~keyIsDown %# Keep looping until a key is pressed
[keyIsDown,secs,keyCode,deltaSecs] = KbCheck(deviceNumber);
end
end
end
I was able to successfully run the above function with some simple plotting routines and replacing the code in get_input with a simple pause statement and a return value. I'm unsure whether KbCheck will work in a thread, but hopefully you will be able to adapt this for your needs.
Here's the documentation for the Parallel Computing Toolbox functions used in the above code: createJob, createTask, submit, waitForState, destroy.
I don't know of a way how you could do this with parallel processing.
However, a feature you might be able to use is the timer object. You would set up the timer object to poll the input mechanism, and, if anything is detected, change the value of a global variable. Then, you start your stimulus routine. In the while-loop in which you're updating the display, you keep checking the global variable for a change from the timer object.
You have to tackle the 20ms latency in your input device. If it's too slow then get another input device. You can get good sub-millisecond timing with proper response boxes.
All this talk about threading is misguided and not applicable to the PTB framework.