ram keeps on filling when program is abruptly closed in matlab - matlab

MAT-lab keeps on acquiring images form video object when program is closed abruptly,is there any way to know whether my program has been stopped abruptly?
it only stops when i type stop(vid), condition: the vid object must be there in work space
if you have cleared vid object by clear all , then MAT-LAB keeps on acquiring image from the camera

I think what you mean is this: You have some matlab code that acquires data from a camera. If your code exits before getting to the point at which you order the camera to stop acquiring data, then the camera keeps going until your RAM is full Please correct me if I'm wrong. If I'm right, I'd advise you use try/catch statements as follows:
start(vid);
try
%some code to use the video data
stop(vid);
catch
stop(vid);
end
Everything inside 'try' will run, and when it has finished, the video capture will be terminated. If something goes wrong and throws an error before it has got as far as the stop(vid); command, then rather than stalling the program it will display the error in the matlab prompt, and then jump to execute any code inside 'catch'. This means that if your code ends suddenly, the stop(vid); command is still run, and you don't run out of RAM.

Related

Multiple GPU code on Matlab runs for few seconds only

I am running the following MATLAB code on a system with one GTX 1080 and a K80 (with 2 GPUs)
delete(gcp('nocreate'));
parpool('local',2);
spmd
gpuDevice(labindex+1)
end
reset(gpuDevice(2))
reset(gpuDevice(3))
parfor i=1:100
SingleGPUMatlabCode(i);
end
The code runs for around a second. When I rerun the code after few seconds. I get the message:
Error using parallel.gpu.CUDADevice/reset
An unexpected error occurred during CUDA execution. The
CUDA error was:
unknown error
Error in CreateDictionary
reset(gpuDevice(2))
I tried increasing TdrDelay, but it did not help.
Something in your GPU code is causing an error on the device. Because the code is running asynchronously, this error is not picked up until the next synchronisation point, which is when you run the code again. I would need to see the contents of SingleGPUMatlabCode to know what that error might be. Perhaps there's an allocation failure or an out of bounds access. Errors that aren't correctly handled will get converted to 'unknown error' at the next CUDA operation.
Try adding wait(gpuDevice) inside the loop to identify when the error is occurring.
If either device 2 or 3 are the GTX1080, you may have discovered an issue with MATLAB's restricted support for the Pascal architecture. See https://www.mathworks.com/matlabcentral/answers/309235-can-i-use-my-nvidia-pascal-architecture-gpu-with-matlab-for-gpu-computing
If this is caused by the Windows timeout, you would see a several second screen blackout.

While loop stuck

I have written a callback function in Matlab. My laptop is communicating with another laptop that is sending it bytes every few seconds that are recorded in a text file. For e.g. the laptop sends "66" and my laptop writes to the file Event_Markers.txt "66" continuously until the other laptop sends something else. The code is below.
The problem that I am currently facing is that in my callback function (below) I use a while loop to continuously write the same "information" (e.g. "66") to the text file until the other laptop sends something else. But this while loop gets stuck. This part is of a larger script that is acquiring data from a spectrometer and adding it to my script and causes everything to become stuck and the rest of the script is not executed. I tried to use an if loop instead of while and it only writes "66" twice instead of writing it continuously. It is, however, writing to the text file as I want it to.
Does anybody know if I need to add some other line of code to stop it becoming stuck?
Thanks!
appenderFile=fopen('Event_Markers.txt','a+t');
s=serial('COM3');
set(s,'BytesAvailable',{#myCallback,appenderFile});
set(s,'BytesAvailableFcnCount',1);
set(s,'BytesAvailableFcnMode','byte');
fopen(s);
function myCallback(s,~,appenderFile)
bytes=(s,'BytesAvailable')
if(bytes==1)
[data count msg] = fread(s,bytes);
end
fprintf(appenderFile,'%d \n',data);
bytes=(s,'BytesAvailable');
while bytes==0
fprintf(appenderFile,'%d \n',data);
bytes=get(s,'BytesAvailable');
end
end
You need to break out of the loop when "something else is sent", something like:
while bytes==0
fprintf(appenderFile,'%d \n',data);
bytes=get(s,'BytesAvailable');
if s ~= 66
break
end
end

matlab parpool failed when stopping mdce on one of workers node [duplicate]

When an out-of-memory error is raised in a parfor, is there any way to kill only one Matlab slave to free some memory instead of having the entire script terminate?
Here is what happens by default when an out-of-memory error occurs in a parfor: the script terminated, as shown in the screenshot below.
I wish there was a way to just kill one slave (i.e. removing a worker from parpool) or stop using it to release as much memory as possible from it:
If you get a out of memory in the master process there is no chance to fix this. For out of memory on the slave, this should do it:
The simple idea of the code: Restart the parfor again and again with the missing data until you get all results. If one iteration fails, a flag (file) is written which let's all iterations throw an error as soon as the first error occurred. This way we get "out of the loop" without wasting time producing other out of memory.
%Your intended iterator
iterator=1:10;
%flags which indicate what succeeded
succeeded=false(size(iterator));
%result array
result=nan(size(iterator));
FLAG='ANY_WORKER_CRASHED';
while ~all(succeeded)
fprintf('Another try\n')
%determine which iterations should be done
todo=iterator(~succeeded);
%initialize array for the remaining results
partresult=nan(size(todo));
%initialize flags which indicate which iterations succeeded (we can not
%throw erros, it throws aray results)
partsucceeded=false(size(todo));
%flag indicates that any worker crashed. Have to use file based
%solution, don't know a better one. #'
delete(FLAG);
try
parfor falseindex=1:sum(~succeeded)
realindex=todo(falseindex);
try
% The flag is used to let all other workers jump out of the
% loop as soon as one calculation has crashed.
if exist(FLAG,'file')
error('some other worker crashed');
end
% insert your code here
%dummy code which randomly trowsexpection
if rand<.5
error('hit out of memory')
end
partresult(falseindex)=realindex*2
% End of user code
partsucceeded(falseindex)=true;
fprintf('trying to run %d and succeeded\n',realindex)
catch ME
% catch errors within workers to preserve work
partresult(falseindex)=nan
partsucceeded(falseindex)=false;
fprintf('trying to run %d but it failed\n',realindex)
fclose(fopen(FLAG,'w'));
end
end
catch
%reduce poolsize by 1
newsize = matlabpool('size')-1;
matlabpool close
matlabpool(newsize)
end
%put the result of the current iteration into the full result
result(~succeeded)=partresult;
succeeded(~succeeded)=partsucceeded;
end
After quite bit of research, and a lot of trial and error, I think I may have a decent, compact answer. What you're going to do is:
Declare some max memory value. You can set it dynamically using the MATLAB function memory, but I like to set it directly.
Call memory inside your parfor loop, which returns the memory information for that particular worker.
If the memory used by the worker exceeds the threshold, cancel the task that worker was working on. Now, here it get's a bit tricky. Depending on the way you're using parfor, you'll either need to delete or cancel either the task or worker. I've verified that it works with the code below when there is one task per worker, on a remote cluster.
Insert the following code at the beginning of your parfor contents. Tweak as necessary.
memLimit = 280000000; %// This doesn't have to be in parfor. Everything else does.
memData = memory;
if memData.MemUsedMATLAB > memLimit
task = getCurrentTask();
cancel(task);
end
Enjoy! (Fun question, by the way.)
One other option to consider is that since R2013b, you can open a parallel pool with 'SpmdEnabled' set to false - this allows MATLAB worker processes to die without the whole pool being shut down - see the doc here http://www.mathworks.co.uk/help/distcomp/parpool.html . Of course, you still need to arrange somehow to shutdown the workers.

How can I save output from Simulink?

I'm a student learning to use MATLAB. For an assignment, I have to create a simple state machine and collect some results. I'm used to using Verilog/Modelsim, and I'd like to collect data only when the state machine's output changes, which is not necessarily every time/sample period.
Right now I have a model that looks like this:
RequestChart ----> ResponseChart ----> Unit Delay Block --> (Back to RequestChart)
| |
------------------------> Mux --> "To Workspace" Sink Block
I've tried setting the sink block to save as "Array" format, but it only saves 51 values. I've tried setting it to "Timeseries", but it saves tons of zero values.
Can someone give me some suggestions? Like I said, MATLAB is new to me, please let me know if I need to clarify my question or provide more information.
Edit: Here's a screen capture of my model:
Generally Simulink will output a sample at every integration step. If you want to only output data when a particular event occurs -- in this case only when some data changes -- then do the following,
run the output of the state machine into a Detect Change block (from the Logic and Bit Operations library)
run that signal into the trigger port of a Triggered Subsystem.
run the output of the state machine into the data port of the Triggered Subsystem.
inside the triggered subsystem, run the data signal into a To Workspace block.
Data will only be saved at time point that the trigger occurs, i.e. when your data changes.
In your Simulink window, make sure the Relative Tolerance is small so that you can generate many more points in between your start and ending time. Click on the Simulation option at the top of the window, then click on Model Configuration Parameters.
From there, change the Relative Tolerance to something small... like 1e-10. After that, try running your simulation again. You should have a lot more points in your output array that you can now save.

What error does "ExtAudioFileWriteAsync -50" indicate?

I'm attempting to write an AAC file from the output stream of an AUGraph, and on playback my file only plays a buzzing noise, and I get the error ExtAudioFileWriteAsync -50.
I'd like to know what it means so that I can search for and destroy the problem.
Thanks to any Core Audio ninjas that can hook a brother up.
In case anyone else has this problem, the -50 error is a kAudio_ParamError error, defined in CoreAudioTypes.h.
Therefore, one of the parameters being passed to ExtAudioFileWriteAsync must be faulty.