Creating delay with a while loop in Matlab - matlab

As a student I am currently working on a Matlab Simulink project. I am quite new to using Matlab/Simulink (few weeks).
I want to implement and run a Matlab “.m” file with which I can open Simulink and start the simulation. The aim is to do a 24h Test with a load cell cut into 1h “pieces” and to save the data to different sheets of an excel file each hour. So my simulation runs for 1h, stops and starts again, and so on. Through Matlab and a “for” loop I do the measures 24 times.
Between measuring steps I have to wait for simulink to finish its measures and saving the file in order for the Simulink window to be able to get closed by close_system('Thesis_SerDatTransm_Simulink').
So I tried to implement the delay with a while loop and by checking if the measures I get fit into an array of the size bigger than 449 (I measure 449 values):
for k=0:1:24
% Load Simulink
load_system('Thesis_SerDatTransm_Simulink.slx')
% Open Simulink
open_system('Thesis_SerDatTransm_Simulink.slx')
% Start Simulation
set_param('Thesis_SerDatTransm_Simulink', 'SimulationCommand', 'Start');
% Save Data
my_cell = sprintf('A%d',k);
xlswrite('file.xlsx',y,my_cell)
% Wait for Simulation
while 1
test=size(y)>=449;
if (test)
close_system('Thesis_SerDatTransm_Simulink')
break
end
end
end
The Problem now is, that program gets stuck at the while loop. Simulink is started, but no simulation or data gathering is done.
So I wondered if anyone could check if something is wrong with my While loop, since the rest of the programm works all fine without the loop (but receiving an error message, that during the simulation, Simulink window can't be closed).
I know there is a way to create a delay with waitforin matlab and create another function which I could call, but I couldn't figure out how to do this yet.
thanks
Regards
hohmchri

The right way to do this is to use the sim function to run your model (not the sequence of load_system, open_system and set_param that you have).
sim will block the execution of m-code until the model completes executing. Data can either be returned into the workspace (when used with no output arguments) or returned as an output from the call to sim. (And then you can write it to Excel as you've done.)
The only reason not to use sim, and perhaps use the commands you have, is if the model takes a long time to initialize, and you don't want to to open and close it every time through the loop. However, even in this case your code isn't correct. The load_system would be outside the loop; the open_system is not required; in your while loop you would poll the model's SimulationStatus property to see if it is still running (not the size of the y variable); and the close_system would be after the loop (as indicated by #m_power in one of the comments).

As written you should use the matlab pause command. This stops your execution for X seconds.
You should also look to optimize your code as m_power states

Related

Save Simulink Scope Data to figure through matlab code

As a student I am currently working on a Matlab Simulink project. I am quite new to using Matlab/Simulink (few weeks).
I am using a load cell from which I gather data through UART and display it on a Matlab Simulink Scope. This works all fine. My next step was to implement and run a Matlab “.m” file with which I can open Simulink and start the simulation. The aim is to do a 24h Test cut into 1h “pieces” and to save the scope data to a figure each hour. So my Simulink simulation runs for 1h, stops and starts again, and so on. Through Matlab and a “for” loop I do the measures 24 times.
What I didn’t figure out:
Save the Simulink Scope Data to a figure through Matlab code, each time one increment in the loop ist done. I can get the figure from my Simulink Block but that’s not what I wanted (by that I mean that I literally get a screenshot from the Simulink Block; just to be clear).
for i=0:1:24
[…]
% Print to JEPG
fig = get_param('Simulink_Project','handle');
saveas(fig,sprintf('Figure%02d.jpeg',i ));
[…]
end
I hope that what I stated, was clear.
Thanks for your help.
Regards
hohmchri

Debugging Simulink model programmatically

I have written a matlab program for a simulink model and taking control through it programmatically, but I am facing one problem while using set_param('testmodel11', 'SimulationCommand', 'start');.
It gives all the values at once, that is gives the entire scope and workplace values all at the same time, but I don't want this. I would like to run the program and execute at that point, seeing only rest of the values should be zero. How can I stop the simulation at that point and fetch plots and values from that point only, the rest should be zero. And ideally have this same behavior for the next break points too?
There is a way to pause the simulation at certain breakpoints (simulation points), plot the output or do whatever is desired of it, and then continue the simulation until the next breakpoint.
However, at any breakpoint, you will get output data from all the time samples till the breakpoint is reached. To isolate data from a certain timestamp, you can calculate its index based on the sample time and extract it from the workspace (output data is stored as an array)
Here is the link to my answer which will be helpful, pls go through it:
https://stackoverflow.com/a/38348315/6580313
Now, in the m-file which you will run when the simulation is paused, you can change the value of the constant block which specifies the next simulation time at which simulation needs to be paused. In the m-file, you can also write a code snippet to access the output data.
Once the simulation continues, it will be paused at the new simulation time specified in the constant block.
Let me know in case you have any queries.
It sounds like you want to use the Simulink Debugger. Check out the documentation for more details on how to use it. The main command-line interface to it is sldebug.

matlab script node in Labview with different timing

I have a DAQ for Temperature measurment. I take a continuous sample rate and after DAQ, calculating temperature difference per minute (Cooling Rate: CR) during this process. This CR and temperature values are inserted into the Matlab script for a physical model running (predicting the temperature drop for next 30 sec). Then, I record and compare the predicted and experimental values in LabVIEW.
What i am trying to do is the matlab model is executing every 30 sec, and send out its predictions as an output from matlab script. One of this outputs helps me to change the Air Blower Motor Speed until next matlab run( eventually affect the temperature drop for next 30 sec as well, which becomes a closed loop). After 30 sec while main process is still running, sending CR and temperature values to matlab model again, and so on.
I have a case structure for this Matlab script. And inside of case structure i applied an elapsed time function to control the timing for the matlab script, but this is not working.
Yes. Short answer: I believe (one of) the reasons the program behaves weird on changed timing are several race conditions present in the code.
The part of the diagram presented shows several big problems with the code:
Local variables lead to race conditions. Use dataflow. E.g. you are writing to Tinitial local variable, and reading from Tinitial local varaible in the chunk of code with no data dependencies. It is not known whether reading or writing will happen first. It may not manifest itself badly with small delays, while big delays may be an issue. Solution: rewrite you program using the following example:
From Bad:
To Good:
(nevermind broken wires)
Matlab script node executes in the main UI execution system. If it is executing for a long time, it may freeze indicators/controls as well as execution of other pieces of code. Change execution system of other VIs in your program (say to "other 1") and see if the situation improves.

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.

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.