Matlab Parallel Computing with Simulink Model - matlab

I'm working on a project in which parallel computing would be a huge advantage. The project simulates multiple Simulink models. I did the simulation with a normal for-Loop, but since it takes days to simulate I decided to try the "parfor"-Loop.
But that's where the problem begins. First I'll give you pictures of my code, the workspace and the Simulink-part which is causing me problems:
Here's my code:
apool = gcp('nocreate');
if isempty(apool)
apool = parpool('local');
end
wpath = pwd;
parfor k = 1:number_of_models
load_system(strcat(wpath,'\Models_Folder\',House(k).model_name));
set_param(House(k).model_name, 'Stoptime', num2str(foreruntime));
set_param(House(k).mask_name, 'Data_contr', num2str(controlvector(k)));
set_param(House(k).mask_name, 'Data_cons', strcat('GlobalData(',num2str(k),').consume.',MaskParam(k).consume_input))
SimOut(k) = sim(House(k).model_name);
end
delete(apool);
The confusing thing is if i delete the column:
SimOut(k) = sim(House(k).model_name);
the code just works fine -> the modelparameters are set in a parfor loop
but if I don't delete the column the following error appears:
Error using Forerunsimple (line 9)
Error evaluating parameter 'Data_cons' in 'model_house_14/House'
Caused by:
Error using parallel_function>make_general_channel/channel_general (line 907)
Error evaluating parameter 'Data_cons' in 'model_house_14/House'
Error using parallel_function>make_general_channel/channel_general (line 907)
Undefined variable "GlobalData" or class "GlobalData".
As you can see in the picture the variable "GlobalData" is defined in the workspace. So in my opinion it should work. Obviously it doesn't. Do you have any idea what could be the problem?

you may want to see this question, IMHO, it is related, and could in fact be the same problem:
MATLAB: What happens for a global variable when running in the parallel mode?
There a workspace global variable appears to be empty, even if it was defined.
user Edric provides a link, and a short explanation, that global variables are not passed to workers (for instance simulink running as parallel).
The link is to this blog entry: "Getting parfor loops up and running":
http://blogs.mathworks.com/loren/2009/10/02/using-parfor-loops-getting-up-and-running/

Related

Error using A3_4 (line 6) Not enough input arguments

This is my code:
%Activity 3.4 An object is thrown vertically with a speed vo reaches at
%height h at a time t.
function t = time(h,vo,g)
t = roots([0.5*g,-vo,h])
%Testing the function
test = time(100,50,9.81)
I've looked through different solutions but still can't figure out why I keep getting this error.
The error is happening on the line t = roots([0.5*g,-vo,h]).
Three comments:
You are probably pushing the Play button in the MATLAB editor. Don't do that. Forget that it even exists. Define h, vo and g in your Command Prompt, then do t = time(h, vo, g); in the Command Prompt. Again, do not push the Play button.
Make sure your working directory is set to where you defined the function time. MATLAB can't find this function that you defined. If you don't know how to do that, check out this from MathWorks: http://www.mathworks.com/help/matlab/ref/cd.html
Your error says it's trying to use a file called A3_4, yet your function is called time. In other words, It looks like you called your file A3_4.m yet it needs to be called time.m. Make sure it's in a file called time.m, then try again. That's one of MATLAB's cardinal rules. When you define a function, the function name and file name need to match.
Do all of those three steps in order, and you will be laughing and singing like these guys below:
(source: kym-cdn.com)

Matlab: What is the best way to keep trying and catching error such that the optimization process restart every time an error is seen?

I need run an optimization process using fminunc for 1000 times, which means I am essentially using a for-loop to loop the optimization process 1000 times. Sometimes, I will get an error like the following:
Error using fminusub (line 16)
Objective function is undefined at initial point. Fminunc cannot continue.
or another error:
Error using chol
Matrix must be positive definite.
Now, it is obvious that these are two different type of errors and when either one of them occurs, the function will exit the for loop , which is painful for me to restart the entire process again. I am wondering whether it is possible to run a statement that try and catch all the errors and restart that single optimization process again until it runs smoothly without encountering any errors.
I just picked up matlab today and I have no idea how to do this ? Is this even possible ?
So far, this is what I have got in my mind:
try
% optimization process
fminunc(.....)
% if it fails
catch err
% regenerate a new initial values then restart optimization process
initial_para = randn(1)
fminunc(...., initial_para)
% PROBLEM is: what if it fails again in the catch statement , how can I try and catch that
end
What is particular with this code is that the only difference between the try and the catch block is that you generate new initial parameters. So what you need to do in the catch is to solve the problem. And the problem is really that you have bad initial parameters, given the code in the question. This is what you have to solve. The way you solve this is really to use a while loop that goes on until it works. So instead of creating new initial parameters and repeat the same process as in try, you should use the code you have. Else you would be forced using recursion (I really would not use a recursion of try-catch! The debugging would be really painful). Ok, but what you do: Fix the problem in catch (which means set a new initial value) and repeat the process until it works.
success = false;
while (~success)
try
% optimization process
fminunc(.....);
success = true;
catch err
% regenerate a new initial values then restart optimization process
initial_para = randn(1);
end
end
So, the code will only reach success=true if the code in the try block works. Else it will go directly to the catch block.

Variable Declaration with the Presence of Nested Functions

Someone on /r/matlab asked me a really interesting question a few days ago related to a Flappy Bird clone submitted to the MATLAB FEX. The poster noticed that if you open the main .m file, stop it in the debugger on the first line, and run a whos(), you see a bunch of variables before they are explicitly defined by the function.
The first thing that I noticed in the editor was the syntax highlighting indicating the presence of nested functions. At a glance, it seems like the variables returned by the whos() are only those that will be defined at some point in the scope of the base function.
You can recreate this with a simpler example:
function testcode
asdf = 1;
function testing
ghfj = 2;
end
end
If you set a breakpoint on the first line and run a whos(), you get
Name Size Bytes Class Attributes
ans 0x0 0 (unassigned)
asdf 0x0 0 (unassigned)
I couldn't seem to find anything explaining this behavior in the documentation for nested functions or related topics. I am not a computer scientist and my programming knowledge is limited to MATLAB and a very small sprinkling of Python. Can anybody explain what is going on? Does it have something to do with how MATLAB compiles the code at run time?
The workspace of a function with nested function is protected. When the function is called, Matlab has to analyze the code to determine which variables are in scope at what part of the function. Remember, variables that are declared in the main function and that are used in a nested function are passed by reference, and can be modified within the nested function even if not explicitly declared as input or output.
To avoid messing up any of the nested functions, and possibly to help speed things up, Matlab does not allow assigning any additional variables to the workspace of that function. For example, if you stop the execution of the code at line 1, and then try assigning a value to a new variable klmn, Matlab will throw an error. This can be a bit frustrating for debugging, but you can always assign ans, fortunately.

Matlab beginner: function that iterates a matrix

I am a beginner of Matlab. I am trying to run this function but there seem to be a syntax error that I cannot understand. The source code is the following.
function print_trace(x)
for rowi=1:size(x,1),
for coli=1:size(x,2),
disp(x(rowi,coli))
end
end
The error encountered is the following:
??? Input argument "x" is undefined.
Error in ==> print_trace at 2
for rowi=1:size(x,1),
Any ideas?
EDIT: here is a screenshot: http://imgur.com/pwPhzhh
EDIT 2:
Trying to see if there are multiple copies running:
>> which('print_trace')
C:\Users\stablum\Dropbox\cm\print_trace.m
EDIT: solution of the problem :)
it seems that I solved the problem, my mistake was running ("play" button) the file of the function instead of just calling the function (which will load the file automatically). I still don't understand why there was this error when the file is run, but at least my problem is solved.
I suppose it is because of the way you call the function.
The error indicates that you don't give the required parameter x. Especially, you seem t o call the function with
print_trace()
or
print_trace
or
print_trace(empty_cell{:})
which leads to the effect that there is no value to be assigned to x.

How can matlab be unable to find an anonymous function?

I get a strange error when running my script:
Unable to find function #(x) exp(x) within H:\blabla\myClass.m.
when I debug I get:
34 b=myAnonymousFunction(a)
K>> myAnonymousFunction(3)
Unable to find function #() exp(x) within HH:\blabla\myClass.m.
K>> class(myAnonymousFunction)
ans =
function_handle
A minimal example I was trying to produce worked fine.
Do You have any Idea where the error comes from and what it means?
Because he obviously can find the definition of insanity...ahh... myAnonymousFunction. Is it just a bug? I read something on matlabcentral but its 7 Years old and doesn't give an explanation.
Further explanation:
I'm running MATLAB 2012 b under Windows 8 64 bit. The source files were originally written under a 64 bit Linux.
I don't think it's relevant but myAnonymousFunction is a parameter to a function in myClass and stored within a cell array. So it's like this:
file myClass.m:
classdef myclass < handle
properties
x=1337;
myAnonymousFunctions;
end
methods
function new = myClass(myAnonymousFunctions)
new.myAnonymousFunction=myAnonymousFunction
end
function show(o)
disp(myAnonymousFunction{1}(o.x));
end
end
end
and gets called like
myMyclass = myClass({#(x)exp(x)})
myMyClass.f();
Possible Workaround: restart Matlab.
After restarting MATLAB the Problem didn't occur ... so far.
I guess buggy ML debugger was buggy.
I also received the same error when using an anonymous function in a class. The function was stored as a field inside a Matlab class as:
dataBlockObj.processStream(dataBlockObj.activeProcessStreamIndex).func=#(x) x;
and I had been debugging the code, however the error occurred while I was running the code on the command line without any breakpoints set. The solution for me was also restarting Matlab. I was running Matlab 2012b 64bit on a Windows 2008 Server.