How to connect matlab scripts - matlab

I have the following problem:
I have written six scripts matlab. In the first script, the user must enter the variable n_strati (a number between 1 and 5). The first script allows you to make choices about computing models based on variables known or unknown , and runs them to n_strato=1. The second third fourth and fifth script follow the same procedure , respectively, for the layers 2-3-4-5, but in which the input parameters (not intended as a value) are different. For example:
for Strato1 performs calculations knowing the input variables A B E (and not C D F) , for Strato2 performs calculations knowing A C E (and not B D F) , for Strato3 knowing the variables B D F (and not A C E).
The sixth takes all the variables of the previous scripts and processes them to obtain the final result.
The first five scripts save the data using the command:
save Strato1 alpha beta gamma
% etc.
and the sixth script them "stores" with the command:
load Strato1
load Strato2
% etc.
But I have to make sure that:
if n_strati==1
I enter the data and choose the models in script1 jumping scripts 2-3-4-5 and proceeding with the final calculation through the script 6 .
if n_strati==2
I enter the data and choose the models for Strato1 in script1 and Strato2 in script2 jumping scripts 3-4-5 and proceeding with the final calculation through the script 6 .
and so on.
I wanted to know: how can I do?
Thank you for your cooperation.

The best way would be avoiding scripts and using functions. Even if you succeed in your plot of using multiple scripts, the code will be a big mess, hard to debug, etc. So the answer is simple:
Say NO to scripts!
It is as easy as adding a signature and declaring your input and output.

Related

How to load .mat files in the folder for parfor in MATLAB

I want to run a parfor loop in MATLAB with following code
B=load('dataB.mat'); % B is a 1600*100 matrix stored as 'dataB.mat' in the local folder
simN=100;
cof=cell(1,simN);
se=cell(1,simN);
parfor s=1:simN
[estimates, SE]=fct(0.5,[0.1,0.8,10]',B(:,s));
cof{s}=estimates';
se{s}=SE';
end
However, the codes seem not work - there are no warnings, it is just running forever without any outputs - I terminate the loop and found it never entered into the function 'fct'. Any help would be appreciated on how to load external data like 'dataB.mat' in the parallel computing of MATLAB?
If I type this on my console:
rand(1600,100)
and then I save my current workspace as dataB.mat, this command:
B = load('dataB.mat');
will bring me a 1 by 1 struct containing ans field as a 1600x100 double matrix. So, since in each loop of your application you must extract a column of B before calling the function fct (the extracted column becomes the third argument of your call and it must be defined before passing it)... I'm wondering if you didn't check your B variable composition with a breakpoint before proceeding with the parfor loop.
Also, keep in mind that the first time you execute a parfor loop with a brand new Matlab instance, the Matlab engine must instantiate all the workers... and this may take very long time. Be patient and, eventually, run a second test to see if the problem persists once you are certain the workers have been instantiated.
If those aren't the causes of your issue, I suggest you to run a standard loop (for instead of parfor) and set a breakpoint into the first line of your iteration. This should help you spot the problem very quickly.

Clean methodology for running a function for a large set of input parameters (in Matlab)

I have a differential equation that's a function of around 30 constants. The differential equation is a system of (N^2+1) equations (where N is typically 4). Solving this system produces N^2+1 functions.
Often I want to see how the solution of the differential equation functionally depends on constants. For example, I might want to plot the maximum value of one of the output functions and see how that maximum changes for each solution of the differential equation as I linearly increase one of the input constants.
Is there a particularly clean method of doing this?
Right now I turn my differential-equation-solving script into a large function that returns an array of output functions. (Some of the inputs are vectors & matrices). For example:
for i = 1:N
[OutputArray1(i, :), OutputArray2(i, :), OutputArray3(i, :), OutputArray4(i, :), OutputArray5(i, :)] = DE_Simulation(Parameter1Array(i));
end
Here I loop through the function. The function solves a differential equation, and then returns the set of solution functions for that input parameter, and then each is appended as a row to a matrix.
There are a few issues I have with my method:
If I want to see the solution to the differential equation for a different parameter, I have to redefine the function so that it is an input of one of the thirty other parameters. For the sake of code readability, I cannot see myself explicitly writing all of the input parameters as individual inputs. (Although I've read that structures might be helpful here, but I'm not sure how that would be implemented.)
I typically get lost in parameter space and often have to update the same parameter across multiple scripts. I have a script that runs the differential-equation-solving function, and I have a second script that plots the set of simulated data. (And I will save the local variables to a file so that I can load them explicitly for plotting, but I often get lost figuring out which file is associated with what set of parameters). The remaining parameters that are not in the input of the function are inside the function itself. I've tried making the parameters global, but doing so drastically slows down the speed of my code. Additionally, some of the inputs are arrays I would like to plot and see before running the solver. (Some of the inputs are time-dependent boundary conditions, and I often want to see what they look like first.)
I'm trying to figure out a good method for me to keep track of everything. I'm trying to come up with a smart method of saving generated figures with a file tag that displays all the parameters associated with that figure. I can save such a file as a notepad file with a generic tagging-number that's listed in the title of the figure, but I feel like this is an awkward system. It's particularly awkward because it's not easy to see what's different about a long list of 30+ parameters.
Overall, I feel as though what I'm doing is fairly simple, yet I feel as though I don't have a good coding methodology and consequently end up wasting a lot of time saving almost-identical functions and scripts to solve fairly simple tasks.
It seems like what you really want here is something that deals with N-D arrays instead of splitting up the outputs.
If all of the OutputArray_ variables have the same number of rows, then the line
for i = 1:N
[OutputArray1(i, :), OutputArray2(i, :), OutputArray3(i, :), OutputArray4(i, :), OutputArray5(i, :)] = DE_Simulation(Parameter1Array(i));
end
seems to suggest that what you really want your function to return is an M x K array (where in this case, K = 5), and you want to pack that output into an M x K x N array. That is, it seems like you'd want to refactor your DE_Simulation to give you something like
for i = 1:N
OutputArray(:,:,i) = DE_Simulation(Parameter1Array(i));
end
If they aren't the same size, then a struct or a table is probably the best way to go, as you could assign to one element of the struct array per loop iteration or one row of the table per loop iteration (the table approach would assume that the size of the variables doesn't change from iteration to iteration).
If, for some reason, you really need to have these as separate outputs (and perhaps later as separate inputs), then what you probably want is a cell array. In that case you'd be able to deal with the variable number of inputs doing something like
for i = 1:N
[OutputArray{i, 1:K}] = DE_Simulation(Parameter1Array(i));
end
I hesitate to even write that, though, because this almost certainly seems like the wrong data structure for what you're trying to do.

What are the relationships between workspace, .m scripts and Simulink models and how can I use them efficiently?

I'm using a lot of MATLAB for a Control class and something is really bumming me out. They want us to use a lot of Simulink even though I find the visual representation not that helpful and the interface between Simulink and MATLAB scripts hard to figure out in general.
So I have a model and I have added scopes for sinks which can save data directly to the workspace when ran from Simulink. However when I use the command sim in the script to directly use the model according to some parameters (stopTime, solving method, etc.) the results are buried in an object which is poorly documented to say the least so say I have:
simout = sim('lab','StopTime','100','Solver','ode1','FixedStep','2');
Now I have an object in my workspace but to access the data I want I need to go 3, hell 4 layers deep sometimes in the members of simout. My first question is :
Is there a way to access directly or at least know what those members are without using the tedious use of who.
I don't want to compile code to access its documentation! And help is not really helpful for those situations.
Why doesn't the Simulink model save the data when invoked like prescribed in the sink properties. I know that the line of code I mentioned overides some of the simulink block prescriptions (e.g. the solving method used).
How to know how simulink models interact with matlab scripts, granted I am a noob in coding in general, but the documentation doesn't really tell me what are the formal definitions of the model and the way it is used in matlab. I am scared at some points the default settings of 'sim' will overide some settings I set up in an earlier model which would prove to be a nasty buisiness to debug.
TL;DR Is there a quick way to access deeply buried members of an object? For example right now I have to do:
simout = sim('lab','StopTime','100','Solver','ode1','FixedStep','2');
who(simout)
ScopeData = (simout.get('ScopeData'))
signals = (ScopeData.signals)
time = (ScopeData.time)
Can I do something more C-ish of the sort of (Simout->ScopeData).signals?
And finally, why is the MATLAB suite presented like it was an app for day-traders when it is used a lot by EE people who in general need to know their coding? Why are libraries with headers and good documentation for what you are importing in your code (e.g. boost, string etc.) not used? This last option might be less pretty by hiding the mechanics, but to be able to write code properly I feel like I have to know most of the underlying mechanics of the code.
Invariably when most people start off using MATLAB or Simulink, they hate it. The main reasons I see for this is people are taught MATLAB very poorly which prevents them from understanding the power of MATLAB and when it should be used.
Before I get into describing how the MATLAB workspace, m files and Simulink are all related let's first define what each of those is separately and a few of the things you can do with them.
The MATLAB Workspace
The MATLAB workspace contains all of the variables you have created in MATLAB either explicitly via the command window or implicitly through running a .m file (don't worry I'll come back to these). The simplest method to add a variable to the MATLAB workspace is to directly type into the command window like
>> A = 1
A =
1
which adds the variable A to the workspace and assigns it a value of 1. Even simpler though is to simple type 1 like
>> 1
ans =
1
which adds the variable ans to the workspace with a value of 1. The default workspace variable for any command executed by MATLAB that is not explicitly assigned to a variable is ans.
The workspace browser in MATLAB displays information about all of the variables currently in the workspace. For instance if we were to execute, in the command window,
>> A = 5;
>> B = [6 8];
>> C = [3 6 7; 9 11 12];
>> D = eye(max(size(C)));
the workspace browser would look something like
Some Helpful Workspace Commands
The save and clear commands are helpful commands that work with the MATLAB workspace. save lets you save variables from the workspace to a file whilst clear lets you remove variables from the workspace, thus freeing up memory. clear all will clear every variable from the workspace.
m Files
An m-file (or script file) is a simple text file with a .m file extension. In it you type MATLAB commands which can be executed sequentially by executing just the m-file in the command window. For instance, lets copy our commands from above and paste them into an m-file called mfile_test.m. Now lets add the command C - A to the bottom of the m-file (note do not append a ; after the command). We can execute this m-file from the command window and see the output of all of commands within it executed sequentially
>> mfile_test.m
ans =
-2 1 2
4 6 7
m Files and Functions
m files can also contain functions. For instance we could write a function that calculates the area and circumference of a circle like
function [A, C] = circle(r)
A = pi*r*r;
C = 2*pi*r;
end
and put it in an m-file called circle.m. We could then use this like
>> circle(5)
ans =
78.5398
where ans now holds the area of a circle with a radius of 5 or
>> [A, C] = circle(5)
A =
78.5398
C =
31.4159
where A holds the area of the circle and C the circumference.
Simulink Models
Simulink is a graphical tool that can be used to model various different types of systems as well as modelling dynamic system behaviour. Simulink is closely embedded into the MATLAB ecosystem which adds additional power to it (again I'll come back to this later when describing the similarities).
Simulink models contain blocks which all exhibit different behaviour. There is also the functionality to create your own Simulink blocks should you need. Models in Simulink are made by connecting blocks of different kinds to emulate the system you want to model.
Simulink is quite extensive and I don't recommend learning it on your own. The best way to learn Simulink is invariably as part of a course, Control Systems or Systems Analysis type courses are ideal for this purpose. For that reason I'm not going to dwell on it for much longer here.
How are the MATLAB Workspace, m Files and Simulink all Related?
Well, the MATLAB workspace is available to both m files and Simulink. Variables in the MATLAB workspace can be used in both m files and Simulink.
m files that contain only scripts (and not functions) will write every variable created in them to the MATLAB workspace. m files that contain only functions won't write any of the new variables used in those functions to the MATLAB workspace. The only way a function will alter variables in the MATLAB workspace is by assigning an output value to ans or if you explicitly declare output arguments when calling the function.
Simulink and the MATLAB workspace have a very similar relationship to m files and the MATLAB workspace. Any variable in the MATLAB workspace is available for use in Simulink (in any part, including configuration). For instance in the below configuration I use the MATLAB workspace variables start_time, stop_time and step_time to set up the parameters of model. Typically I would define these in an m-file before I run my Simulink model with sim(). This is how we can relate all 3 together.
Simulink can write variables to the MATLAB workspace by adding output arguments to the sim() command. However, as you've found this can be quite nasty to navigate and extract what you really want! A better approach would be to use the Data Import/Export options in Simulink coupled with a To Workspace block to grab the outputs that you are concerned with so that you can ignore everything else.
Below I have a screenshot of the Simulink Data Import/Export pane. You can see there are options in here for us to send variables to the MATLAB workspace. Typically, the most common you would need is tout which will be a range given by start_time:step_time:stop_time from the earlier configuration pane. Other areas that would be of primary interest in this screen would be xInitial and xout which are used in Root Locus analysis.
However, all that aside one of the best blocks in Simulink is the To Workspace block. This block can be used to store variables directly in the MATLAB workspace and is one of the keys to being able to link MATLAB and Simulink. You get the power of Simulink but the computational and plotting abilities of MATLAB. I've included a screenshot of it below as well as a typical configuration I would use. The default Save Format for this block is Timeseries, however, I recommend changing this to Array as it will make your life much easier.
OK, where was I? I feel like I'm giving a lecture instead of writing an answer!
A Practical Explanation
Simulink Model
So now let's put everything we've learned into practice with a simple example. First we are going to create a simple Simulink model like this
Now we'll set up our configuration for this, as before for the Solver section
We'll also untick Limit data points to last: in the Data Import/Export section
And, that's it. Our simple Simulink model has been created and setup. For the purposes of this answer, I'm saving mine as stackoverflow_model.slx.
MATLAB Script
Now we'll create simple MATLAB script (m-file) called stackoverflow_script.m that will set up the necessary variables for our Simulink model by adding them to the MATLAB workspace. We'll then call our Simulink model and check what new variables it added to the workspace. And, finally we'll generate a simple plot to show the benefits of this approach.
So here is the MATLAB script
% Script developed to describe the relationship between the MATLAB
% workspace, m-files and Simulink
close all
clear all
% Initialise variables
start_time = 0;
stop_time = 10;
step_time = (stop_time - start_time) / 1000; % Creates 1000 + 1 points
% Choose k
k = 60;
% Execute Simulink model
sim('stackoverflow_model');
whos % To display variables returned from Simulink
% Plot results
figure;
plot(tout, yout, 'r');
title('Sample Plot');
xlabel('Time (s)');
ylabel('Output');
Putting it All Together
Now we execute this script in the command window with stackoverflow_script and sit back and marvel at the POWER of MATLAB and Simulink combined.
>> stackoverflow_script
Name Size Bytes Class Attributes
k 1x1 8 double
start_time 1x1 8 double
step_time 1x1 8 double
stop_time 1x1 8 double
tout 1001x1 8008 double
yout 1001x1 8008 double
We can see from the output above that all of the variables Simulink needs (k, start_time, step_time and stop_time) are all in the MATLAB workspace. We can also see that Simulink adds 2 new variables to the MATLAB workspace tout and yout which are simple 1001x1 vectors of doubles. No nasty structs to navigate.
And finally, this produces a nice plot
And so that concludes our whistle stop tour through MATLAB, m files and Simulink! I hope you've enjoyed it as much as I did writing it!
P.S. I haven't checked this for spelling or grammar mistakes so edits are very much welcome ;)
General
Well to put it short workspace is the variable-environement you are working in. If you run a script, your workspace is 'base', which is the same the console uses. So Matlab does have different environements, one is a kind of included environement known as path, the other one is for variables, known as workspace.
Simulink uses a different one, which prevents shadowing variable names I guess.
To check check members in the current workspace use who
To write members to another workspace use assignin
To run something in a specified workspace use evalin
Your Questions
1.
Who lists all the variables in the current workspace you don't need it for the thing you wanna do.
The whole simulink documentation isn't that good...
2.
It does...
3.
If you run a script and define variables they are defined in the base workspace. When you specify a variable in simulink by just entering its name (for example a), it does load it from the base workspace (hence this way arround no problems).
The other way arround is to either use the given export blocks, or specify export values in your own blocks by either using global or assignin.
4.
If you open the scope block and hit the options-buttion (the little gear), you can select an export option. You can aswell specify the type you wan't to use. You seem to use the struct with time option, which is the one with the most lvls, I'd suggest to use the array-type if your problem is just the fact that it is a struct.
You can also just use the Outputblock to specify the export type and name.
So I'd go with:
sim('modelname');
signals=ScopeData.signals;
time=ScopeData.time;
Or when specified as an array:
sim('modelname');
signals=ScopeData(:,2);
time=ScopeData(:,1);
In the example above I don't specify the way the model is run, however you can also specify it as you posted.

how to 'zero' all variables at each loop iteration

I have written a script describing a dynamic biological process in matlab; the input to which is a year of daily temperature values.The model runs for a year on this daily timestep carrying out different calculations required for the process.
I have thirty years of temperature data (matrix of size 365*30) and I intend to write a 'for loop' at the start of the script in order to use each year of daily data consecutively. I have about 5 variables that are the output from the script, which I intend to output to a txt/csv file at each iteration. My problem is that there are approximately 80 variables within the model and I would like to zero them all at each iteration of the outermost loop (the temperature input). I would like to do this in an efficient manner rather than having to individually zero all the variables. Does anyone know how to do this?
I have been looking at using the 'who' function to list all the variables and I'm thinking that it could be used somehow to zero everything. I have tried letting x = who; which seems to produce a list of all the variables in inverted commas. But obviously; trying to let x = 0 after that just redefines x. I was also thinking of just using 'clear all' but I think this would really slow the model down as it would be 'starting from scratch' redefining all the variable at each loop?
Any help would be appreciated.
First of all, if you have 80 variables you are probably doing something strange. Consider to combine them into vectors or arrays for example.
That being said, there are two situations I can think about:
You already initialize all your variables somewhere
In this case the solution is simple: move the initialization to the start of your outer loop.
You don't initialize anything (bad practice, especially if you are concerned about performance)
In this case you should put a function inside your loop, that only returns your output variables and not all these loose intermediate variables.
Perhaps a combination of these two methods can also apply, but really I would recommend not to use 80 different variables! And initialize any variable that you need to use.
A compact syntax to initialize scalars would be:
[a, b,c] = deal(0);

MATLAB: alternatives to calling feval in ode45

I hope I am on topic here. I'm asking here since it said on the faq page: a question concerning (among others) a software algorithm :) So here it goes:
I need to solve a system of ODEs (like $ \dot x = A(t) x$. The Matrix A may change and is given as a string in the function call (Calc_EDS_v2('Sys_EDS_a',...)
Then I'm using ode45 in a loop to find my x:
function [intervals, testing] = EDS_calc_v2(smA,options,debug)
[..]
for t=t_start:t_step:t_end)
[Te,Qe]=func_int(#intQ_2_v2,[t,t+t_step],q);
q=Qe(end,:);
[..]
end
[..]
with func_int being ode45 and #intQ_2_v2 my m-file. q is given back to the call as the starting vector. As you can see I'm just using ode45 on the intervall [t, t+t_step]. That's because my system matrix A can force ode45 to use a lot of steps, leading it to hit the AbsTol or RelTol very fast.
Now my A is something like B(t)*Q(t), so in the m-file intQ_2_v2.m I need to evaluate both B and Q at the times t.
I first done it like so: (v1 -file, so function name is different)
function q=intQ_2_v1(t,X)
[..]
B(1)=...; ... B(4)=...;
Q(1)=...; ...
than that is naturally only with the assumption that A is a 2x2 matrix. With that setup it took a basic system somewhere between 10 and 15 seconds to compute.
Instead of the above I now use the files B1.m to B4.m and Q1.m to B4.m (I know that that's not elegant, but I need to use quadgk on B later and quadgk doesn't support matrix functions.)
function q=intQ_2_v2(t,X)
[..]
global funcnameQ, funcnameB, d
for k=1:d
Q(k)=feval(str2func([funcnameQ,int2str(k)]),t);
B(k)=feval(str2func([funcnameB,int2str(k)]),t);
end
[..]
funcname (string) referring to B or Q (with added k) and d is dimension of the system.
Now I knew that it would cost me more time than the first version but I'm seeing the computing times are ten times as high! (getting 150 to 160 seconds) I do understand that opening 4 files and evaluate roughly 40 times per ode-loop is costly... and I also can't pre-evalute B and Q, since ode45 uses adaptive step sizes...
Is there a way to not use that last loop?
Mostly I'm interested in a solution to drive down the computing times. I do have a feeling that I'm missing something... but can't really put my finger on it. With that one taking nearly three minutes instead of 10 seconds I can get a coffee in between each testrun now... (plz don't tell me to get a faster computer)
(sorry for such a long question )
I'm not sure that I fully understand what you're doing here, but I can offer a few tips.
Use the profiler, it will help you understand exactly where the bottlenecks are.
Using feval is slower than using function handles directly, especially when using str2func to build the handle each time. There is also a slowdown from using the global variables (and it's a good habit to avoid these unless absolutely necessary). Each of these really adds up when using them repeatedly (as it looks like here). Store function handles to each of your mfiles in a cell array and either pass them directly to the function or use nested function for the optimization so that the cell array of handles is visible to the function being optimized. Personally, I prefer the nested method, but passing is better if you will use those mfiles elsewhere.
I expect this will get your runtime back to close to what the first method gave. Be sure to tell us if this was the problem or if you found another solution.