Input of stepImpl is entire array when using step in a script - matlab

If I use step(sys,x) in a script after constructing a system object, the entirety of x is passed through as a vector to stepimpl instead of sample by sample input.
On the other hand, if I perform step(sys,s) where s is a scalar instead and iterates this line of code, the state of 'sys' is reset on each call of step.
For example:
SFTRLS_obj = SFTRLS;
for i = 1 : N
step(SFTRLS_obj,d_dx(i),dx(i));
end
What is the proper way to use a system object in a script and 'propagate' input samples to the system object?

You should have iteration loop yourselves and call step in the iteration loop. You should use functions if you want to reuse code with System objects. Within the function you should declare System objects as persistent and create it once as shown in the code below. This will create the System objects once and will keep the states in each call to function.
function y = useSystemObjects(u)
persistent obj
if isempty(obj)
% Create System object once
obj = MySystemObject;
end
y = step(obj, u);
% Use the above function from MATLAB command line
data = rand(100,1);
y = zeros(100,1);
for n=1:100
y(ii) = useSystemObjects(data(ii));
end
If you use scripts, the object is getting recreated in each call to the script which destroys the states.

Related

Running Matlab script many times

So I have a matlab.m file script. When the file runs. It generates a vector. I want to save that vector and rerun the script all over again. How do I put a loop on the entire script file and create a vector_{i}, where the index enters the name of the file? I would post the code but it wont work without the data on my desktop.
[data,labels]=xlsread('C:\Users\Hilbert\Desktop\matlab\matlabdata_abe.xlsx');
gdp=log(data(:,1)./lagmatrix(data(:,1),1)) %GDP
ip=log(data(:,2)./lagmatrix(data(:,2),1)) %IP
tnx=data(:,3) %TNX
m2=log(data(:,4)./lagmatrix(data(:,4),1)) %M2
cpi=log(data(:,5)./lagmatrix(data(:,5),1)) %CPI
ffed=log(data(:,6)./lagmatrix(data(:,6),1)) %FedFund
Dgdp=gdp
inflation=cpi
Dm2=m2
ffr_=ffed
data=[Dgdp(54:length(cpi)), inflation(54:length(cpi)), Dm2(54:length(cpi)), ffr_(54:length(cpi)) ];
data_L1=lagmatrix(data,1)
data_L2=lagmatrix(data,2)
data_L3=lagmatrix(data,3)
data_L4=lagmatrix(data,4)
mat=[ones(1,size(data_L1',2));data_L1';data_L2';data_L3';data_L4']
mat=mat(:,5:end)
X=[data';data_L1';data_L2';data_L3']
X=X(:,5:end)
mat=mat';
X=X'
Fhat=(inv(mat'*mat) * mat'*X)';
nobs=size(data,1)
p=4
yhat= mat*Fhat'
yhat=yhat(:,1:4)
data_sample=data(5:nobs,:)
res=data_sample - yhat
res_{loopindexnumber}=res %saves the vector and re-runs the entire cost again the idea is to bootstrap the data by running many simulations and saving the residual vector
Make the script a function. And then execute the function in a loop how many times you want. For example:
function res = my_function(k)
% your script goes here.
% the function is saved in my_function.m file
% some calucations producing return_vector using k parmeter
res = return_vector
Later on, just run a for loop over the function and store the results to a cell array:
for k = 1:10
A{k} = my_function(k)
end
Make the script a function. And then execute the function in a loop how many times you want. For example:
function res = my_function(k)
% your script goes here.
% the function is saved in my_function.m file
% some calucations producing return_vector using k parmeter
res = return_vector
Later on, just run a for loop over the function.
for k = 1:10
assignin('base', ['A_', num2str(k)], my_function(k))
end

How does function work regarding to the memory usage?

When you are using function in MATLAB you have just the output of the function in the work space and all the other variables that maybe created or used in the body of that function are not shown. I am wondering how does function work? Does it clear all other variables from memory and just save the output?
function acts like a small, isolated programming environment. At the front end you insert your input (e.g. variables, strings, name-value pairs etc). After the function has finished, only the output is available, discarding all temporarily created variables.
function [SUM] = MySum(A)
for ii = 1:length(A)-1
SUM(ii) = A(ii)+A(ii+1);
kk(ii) = ii;
end
end
>> A=1:10
>> MySum(A)
This code just adds two consecutive values for the input array A. Note that the iteration number, stored in kk, is not output and is thus discarded after the function has completed. In MATLAB kk(ii) = ii; will be underlined orange, since it 'might be unused'.
Say you want to also retain kk, just add it to the function outputs:
function [SUM,kk] = MySum(A)
and keep the rest the same.
If you have large variables that you only use up to a certain point and wish them not clogging up your memory whilst the function is running, use clear for that:
function [SUM] = MySum(A)
for ii = 1:length(A)-1
SUM(ii) = A(ii)+A(ii+1);
kk(ii) = ii;
end
clear kk
end

Efficient way of passing data between MATLAB functions

I am solving a very large optimization problem. The objective function and constraint function needs numerous data. Currently I am passing the data as a structure to them.
myFS(X, Dat, g_Index, f_Index) % Dat is a structure which includes many variables
Do you think it's an efficient way to reduce the elapsed time?
What better alternatives do exist?
Is this what the given answer, regarding to class definition, means?
%% First we define the class in a separate file:
classdef myDataStructure < handle
properties
NRES;
NOBJ;
NVAR;
end
methods
function obj = myDataStructure()
end
end
end
%% In another file where the main program is, we initialize the class.
Dat = myDataStructure();
%% Initialize
Dat.NRES = 1;
Dat.NOBJ = 1;
Dat.NVAR = 1;
[myF, Dat_updated] = BBB(Dat);
%% Here we define the function and use the class
function [f, CalssDat] = BBB(CalssDat)
x = CalssDat.NRES;
y = CalssDat.NOBJ;
z = CalssDat.NVAR;
f = x + y + z;
CalssDat.NOBJ = 2;
end
As far as I know, MATLAB does not actually copy the content of the data you pass to a function until the point when you modify it in the function itself - in which case it makes a local copy and that takes some CPU time.
Therefore, as long as Dat doesn't change inside myFS(), what you are doing now does not add any CPU overhead. In case you do change the values of Dat inside myFS() and want to return it, I can think of two ways to optimise it:
You can declare myFS() as: function [Dat, anythingElse] = myFs(X,Dat,g_Index, f_Index), which should prevent matlab from making a local copy.
Another approach is to use a class that derives from handle and have Dat be a member of that. This way, whenever you pass the object containing Dat, you only pass the object handle and not a copy of the object itself.
Example of the second approach:
classdef myDataStructure < handle
properties
p1FromDat;
p2FromDat;
% .
% .
% .
pNFromDat;
end
methods
function obj = myDataStructure()
% Add initialization code here if you want. Otherwise p1FromDat
% ... pNFromDat are accessible from outside
end
end
end
Than, in your code:
Dat = myDataStructure();
Dat.p1FromDat = 1;
Dat.p2FromDat = 1;
And in your myFs() you use Dat exactly the same way as you used before.
Because myDataStructure derives from handle, the data inside will not be copied when you pass Dat around.
Do be careful with this, because when you change Dat in myFS(), the values will be changed outside the scope of myFS() as well.

How to pass matrix by reference or get the return value of function

I have a 1 x 118 matrix called current_load that I need to update periodically. This matrix resides in the main workspace of Matlab (as shown in the code bellow).
current_loads = zeros(1, 118);
for col=1:118
current_loads(1,col)=10; %// Initially give all nodes a current load of 10
end
recursive_remove(current_loads); %calling function
This matrix will be passed to a function call recursive_remove (shown bellow).
function updater = recursive_remove( current_load )
current_load(1,3) = 2.6; %// This update can't be seen from main ??
%this function will be called recursively later
end
But whatever updates I do to this current_load matrix from the function, it will not get updated since I don't know how to pass it by reference.
I am new to Matlab. I would greatly appreciate if you can show with an example how to handle this
EDIT: "How to pass parameter by reference in Matlab"
You can solve your problem passing your arguments by reference
You need a handle class
Handle Classes
Objects that share references with other objects
this is, create a file called HandleObject.m with this code:
classdef HandleObject < handle
properties
Object=[];
end
methods
function obj=HandleObject(receivedObject)
obj.Object=receivedObject;
end
end
end
Then you can do something like this
Object = HandleObject(your matrix)
yourFunction(Object)
And inside your function
function yourFunction(myObject)
myObject.object = new matrix;
end
With that you can achieve some kind of pass by reference and avoid getting a lot of copies trought your program.
The output of the function recursive_remove hasn't been defined and so you ouput can't be used anywhere else.
In matlab you define outputs of functions with square brackets as below.
function [ output1, output2 ] = recursive_remove( input1, input2 )
The outputs can now be passed into other MATLAB docs - functions.
When calling the function in the example above in a different function as you did in your first bit of code you would call it as shown:
current_loads = zeros(1, 118);
for col=1:118
current_loads(1,col)=10; %Initially give all nodes a current load of 10
end
[ output1, output2 ] = recursive_remove( input1, input2 ); %calling function
With this syntax you can take output1 and call it in the input of your next function recursive_remover

Using Matlab Parfor with 'Eval'

I am trying to execute a parfor loop within a parent script for Matlab.
I want to calculate the implied volatility of an option price, and then create a new column within a preexisting dataset with the results.
load('/home/arreat/Casino/names.mat')
name = char(names(i))
%Loop over n rows to populate columns in dataset named using variable 'name(i)'
rows = eval(['length(',name,')'])
parfor n=[1:rows]
%Calculate implied volatility using blsimpv(Price, Strike, Rate, Time, Value, Limit,Yield, Tolerance, Class)
BidIV = blsimpv(eval([name,'.UnderlyingPrice(n)']),...
eval([name,'.Strike(n)']),...
RiskFree/100,...
eval([name,'.Lifespan(n)'])/252,...
eval([name,'.Bid(n)'])+.01,...
10,...
0,...
1e-15,...
eval([name,'.Type(n)'])...
)
eval([name,'.BidIV(n,1) = double(BidIV);']);
%Loop and add implied volatility (BidIV) to a column with n number of
%rows.
end
The problem arises with the 'eval()' calculation in the parfor loop. Mathworks suggested that I should turn the whole script into a function, and then call the function within the parfor loop.
While I work on this, any ideas?
Instead of calling eval all the time, you can call it once outside the loop, e.g. data = eval(name), and then use data.Strike etc inside the parfor loop.
To avoid calling eval at all, do the following:
%# load mat-file contents into structure allData, where
%# each variable becomes a field
allData = load('/home/arreat/Casino/names.mat');
data = allData.(name);