Embedded Matlab: Problem with persistent variables - matlab

I wrote some function, that makes use of persistent variables, for example:
function y = integrator(x, t)
persistent yr; %result
...
and then, if I call it only once in a cycle, everything works fine:
x = integrator(x_dot, t);
but if I want to call it twice with different arguments, it will give wrong results:
x = integrator(x_dot, t);
y = integrator(y_dot, t);
This is not unexpected, but how can I deal with that? Use something different (non-persistent) variables or what?
I'm used to deal mostly with Simulink and the solution is not obvious to me.

You could use a closure for this:
function integrator_handle = make_integrator(yr)
function y = integrator(x, t)
y = x + yr;
yr = yr + 1;
end
integrator_handle = #integrator; % (1)
end
To use:
>> integrator1 = make_integrator(0); % 0 is the initial value for yr
>> integrator2 = make_integrator(1);
integrator1 and integrator2 are now stateful function handles, essentially closures that have captured the state of yr as it was at the point where the function handle was created (the line marked with the comment "% (1)"). They can be invoked using parenthesis-indexing, which looks just like function invocation:
y = integrator1(x, t);
Any modifications to yr during the execution of the function handle will be retained with the function handle, so in my example above, yr will keep incrementing by one each time an integrator is called, but only for that particular instance of the integrator.

The best solution would change what you have to something like:
function [y, yr] = integrator(x, t, yr)
if nargin < 3
yr = []; % will behave identically to persistent when yr is not given
end
Now you can make repeated calls as:
[x,xr] = integrator(x, t);
[x,xr] = integrator(x, t, xr);
[y,yr] = integrator(x, t);
[y,yr] = integrator(x, t, yr);
Though I wouldn't recommend it, there is a way to keep your current implementation and nearly achieve your desired result. It's possible to clear persistent variables by clearing the function. This will allow you to "reset" the persistent variable, which means this sequence of calls should work:
x = integrator(x_dot, t);
clear integrator;
y = integrator(y_dot, t);
But note that this will likely not produce the expected result when calling
x = integrator(x_dot, t);
clear integrator;
y = integrator(y_dot, t);
clear integrator;
x = integrator(x_dot, t);
Whereas in the solution I suggest first you can call
[x,xr] = integrator(x, t);
[y,yr] = integrator(x, t);
[x,xr] = integrator(x, t, xr);
[y,yr] = integrator(x, t, yr);
and the results will maintain state as expected.

You could just send and return the yr variable to the function each time. For your code above you would need to have a x_yr variable and a y_yr variable. It may not be very elegant, but it would work.
If you only want two instances of this function (as above with x and y) then you could make two functions that are identical except in name like xintegrator and yintegrator. Or, you could have yr be an array and have a parameter sent when calling integrator specifying which value in the array to use.

Related

Calling if else output to other script

I have written a function called "tension.m" in which I have used if else condition as shown below.
function [T,T_earlyvalues,T_latervalues] = tension(u,sigma,G,N,K)
%the values of sigma,G,N,K can be taken arbitrary.
sigma=2; G=3;N=8;K=1; v=1;
w=2.2;
if u<w
T =v*sqrt(sigma+G^2/(N-K));
T_earlyvalues=T;
else
T=(2*v)*sqrt(sigma+G^2/(N+K));
T_latervalues=T;
end
Now in another script "myvalues.m" I need to call T_earlyvalues and T_latervalues separately.
%have some coding before this part
sigma0=2400; lambda=1.3; v=2; sigma=2; G=3;N=8;K=1;
u=0:0.01:5;
T=tension(u,sigma,G,N,K);
T_earlyvalues=tension(u,sigma,G,N,K);
T_latervalues=tension(u,sigma,G,N,K);
deltaA=T_earlyvalues*sigma0*pi;
deltaB=T_latervalue*lambda*pi/2;
%have some coding after this part
How could I call the said values which are under if-else statement from tension.m function to myvalues.m script?
You have defined the tension function such that it returns three outputs.
If you call that function by requiring only one output, the function returns the first value, in your case, T
This implies that
T=tension(u,sigma,G,N,K);
shoud work since T is the first output parameter
T_earlyvalues=tension(u,sigma,G,N,K);
T_latervalues=tension(u,sigma,G,N,K);
are not working, since, actually tension returns the first value (T, whjikle you are expecting the second and the third respectively.)
You can cahnge the two above calls this way:
[~,T_earlyvalues,~]=tension(u,sigma,G,N,K);
[~,~,T_latervalues]=tension(u,sigma,G,N,K);
The ~ allows to avoid the function return the output paraemter.
You can find additional information here
Notice that in your function T_earlyvalue is not set in the else block, same for T_latervalue in the if block.
This will generate an error such as
Output argument T_earlyvalue (and maybe others) not assigned during call to tension
or
Output argument T_latervalues (and maybe others) not assigned during call to tension
You can initialize the output values to default values, at the beginning of the function, for example:
T=NaN
T_earlyvalue=NaN
T_latervalues=NaN
You can then use these special values (or any other you want to use) to trace, for example, if the if block has been executed or the else.
There seem to be a number of issues here, not the least of which is some confusion about how output argument lists work when defining or calling functions. I suggest starting with this documentation to better understand how to create and call functions. However, this issue is somewhat moot because the larger problem is how you are using your conditional statement...
You are trying to pass a vector u to your function tension, and from what I can tell you want to return a vector T, where the values of T for u < w are computed with a different formula than the values of T for u >= w. Your conditional statement will not accomplish this for you. Instead, you will want to use logical indexing to write your function like so:
function [T, index] = tension(u, sigma, G, N, K)
T = zeros(size(u)); % Initialize T to a vector of zeroes
w = 2.2;
index = (u < w); % A logical vector, with true where u < w, false where u >= w
T(index) = u(index)*v*sqrt(sigma+G^2/(N-K)); % Formula for u < w
T(~index) = 2*(u(~index)-v)*sqrt(sigma+G^2/(N+K)); % Formula for u >= w
end
Now you can call this function, capturing the second output argument to use for identifying "early" versus "late" values:
sigma0 = 2400; lambda = 1.3; v = 2; sigma = 2; G = 3; N = 8; K = 1;
u = 0:0.01:5;
[T, earlyIndex] = tension(u, sigma, G, N, K); % Call function
T_earlyvalues = T(earlyIndex); % Use logical index to get early T values
T_latervalues = T(~earlyIndex); % Use negated logical index to get later T values
And you can then use the subvectors T_earlyvalues and T_latervalues however you like.

MATLAB: Slow Read-in of constant variables in Script Function

In the latest MATLAB release, I am using the feature of local functions in the script to simplify and shorten the code.
Right now I have a simple script that does mathematical calculations, up to millions of iterations in a for loop. From the loop, I extracted the mathematical part as it is used in multiple independent loops. However, I have the problem with speed and constant variables that need to be in the function. If I write the code without the local function, it is fast, but in the case of using the function, it is 10x slower.
I think it is due to the repetitive read-in of variables in the function. If the read-in happens from a file, it takes forever. The best I have achieved is by using evalin function to call in variables from the base workspace. It works, but as I mentioned, it is 10x slower than without a separate local function.
How to overcome this?
The structure looks like this:
load('Data.mat'); r=1; %Reads variables L,n
for Lx = L1:Ld:L2
for x = x1:d:x2
Yx(r) = myF(x); r=r+1
end
end
%A few more different loops...
function y = myF(x)
L = evalin('base','L');
n = evalin('base','n');
...
a = (x-L)^2; b = sin(a)-n/2; ... y=b*a/L;
end
You will want to explicitly pass the variables as additional input arguments to myF so that you don't have to load them every time. This way you don't have to worry about calling evalin or loading them from the file every iteration through the loop.
load('Data.mat'); r=1; %Reads variables L,n
for Lx = L1:Ld:L2
for x = x1:d:x2
Yx(r) = myF(x, L, n); r=r+1
end
end
function y = myF(x, L, n)
a = (x-L)^2; b = sin(a)-n/2;
y=b*a/L;
end
If for some reason you can't modify myF, just turn the entire thing into a function and make myF a subfunction and it will therefore automatically have access to any variable within the parent function. In this case you'll also want to assign the output of load to a variable to prevent strange behavior and not have issues with adding a variable to a static workspace
function myfunction()
data = load('Data.mat');
L = data.L;
n = data.n;
for Lx = L1:Ld:L2
for x = x1:d:x2
Yx(r) = myF(x);
r=r+1
end
end
function y = myF(x)
a = (x-L)^2; b = sin(a)-n/2;
y=b*a/L;
end
end
A third alternative is to take a hard look at myF and consider whether you can vectorize the contents so that you don't actually have to continuously call it millions of times.
You could vectorize it by doing something like
[Lx, x] = ndgrid(L1:Ld:L2, x1:d:x2);
a = (x - L).^2;
b = sin(a) - (n / 2);
Yx = (b .* a) ./ L;

MATLAB function handles and parameters

When I type help gmres in MATLAB I get the following example:
n = 21; A = gallery('wilk',n); b = sum(A,2);
tol = 1e-12; maxit = 15;
x1 = gmres(#(x)afun(x,n),b,10,tol,maxit,#(x)mfun(x,n));
where the two functions are:
function y = afun(x,n)
y = [0; x(1:n-1)] + [((n-1)/2:-1:0)'; (1:(n-1)/2)'].*x+[x(2:n); 0];
end
and
function y = mfun(r,n)
y = r ./ [((n-1)/2:-1:1)'; 1; (1:(n-1)/2)'];
end
I tested it and it works great. My question is in both those functions what is the value for x since we never give it one?
Also shouldn't the call to gmres be written like this: (y in the #handle)
x1 = gmres(#(y)afun(x,n),b,10,tol,maxit,#(y)mfun(x,n));
Function handles are one way to parametrize functions in MATLAB. From the documentation page, we find the following example:
b = 2;
c = 3.5;
cubicpoly = #(x) x^3 + b*x + c;
x = fzero(cubicpoly,0)
which results in:
x =
-1.0945
So what's happening here? fzero is a so-called function function, that takes function handles as inputs, and performs operations on them -- in this case, finds the root of the given function. Practically, this means that fzero decides which values for the input argument x to cubicpoly to try in order to find the root. This means the user just provides a function - no need to give the inputs - and fzero will query the function with different values for x to eventually find the root.
The function you ask about, gmres, operates in a similar manner. What this means is that you merely need to provide a function that takes an appropriate number of input arguments, and gmres will take care of calling it with appropriate inputs to produce its output.
Finally, let's consider your suggestion of calling gmres as follows:
x1 = gmres(#(y)afun(x,n),b,10,tol,maxit,#(y)mfun(x,n));
This might work, or then again it might not -- it depends whether you have a variable called x in the workspace of the function eventually calling either afun or mfun. Notice that now the function handles take one input, y, but its value is nowhere used in the expression of the function defined. This means it will not have any effect on the output.
Consider the following example to illustrate what happens:
f = #(y)2*x+1; % define a function handle
f(1) % error! Undefined function or variable 'x'!
% the following this works, and g will now use x from the workspace
x = 42;
g = #(y)2*x+1; % define a function handle that knows about x
g(1)
g(2)
g(3) % ...but the result will be independent of y as it's not used.

How does one pass a function with some fixed argument as an argument in MATLAB

I want to pass a function that has arguments to another function that takes the function handler (pointer) as an argument, but some of the arguments to the function handler need to be fixed. How does one do this in MATLAB?
Concretely I want to minimize a function h(eta) using fminsearch(fun,x0). One obvious issue is that if I pass all the arguments in x0 it will minimize it with respect to all the arguments but that isn't what I want to do. What I really want to do is instead:
I have tried the following and it seems to work as far as I tested it:
function [ h ] = function_returner( x )
%
t = -10000;
h = #(eta)-10*x + t + eta^2;
end
and the script to test it:
h = function_returner(0);
h(3) %-9991
[x,fval,exitflag] = fminsearch(h,[10]) %returns [0, -10000, 1]
returns the correct minimum and the correct value of x at which the minimum is obtained. The thing that I wanted to make sure is that the variables that are fixed of h indeed remain fixed after I returned the function handler. i.e. if h is passed around, how does one make sure that the variables don't change value just because they go into an environment that has the same variables names as in the function handler?
I also wrote:
x = inf;
t = inf;
eta = inf;
h = function_returner(0);
h(3) %-9991
[x,fval,exitflag] = fminsearch(h,[10]) %returns [0, -10000, 1]
and it seems to go unaffected (i.e. it works as I want it to work). But just to be on the safe side, I was hoping there was not a some weird edge condition that this doesn't work.
You are worrying unnecessarily. :-) The thing is, when you create an anonymous function, all the outer variables that are used for its definition are frozen, so you don't need to worry that the function will change behavior behind your back via modified parameters. To test this, try this script:
a = 1;
b = 2;
f = #(u,v) u*a + v*b;
x = f(1,1); %// x is 3 = 1*1 + 1*2
a = 2;
b = 3;
g = #(w) f(w,a)
y = g(1); %// y is 5 = f(1,2) = 1*1 + 2*2

Why can't I pass a function handle to fsolve, but I can write an equivalent anonymous function in fsolve?

I find this somewhat odd. I am currently writing a simple function to solve a system of equations using fsolve. Here is what I have:
%Variable Declarations
I0 = 10e-12;
n = 1;
Vt = 0.0259;
R = 10e3;
Vs = 3;
%Function 1 (Some may recognize that this is the Shockley Diode Equation, if anyone cares...)
i1 = #(v1)(I0) * (exp((v1)/(n*Vt))-1);
%Function 2
i2 = #(v1) ((Vs-v1)/R);
%This is what I originally tried
h = #(v1) i1(v1)-i2(v1);
fsolve(h(v1), 1)
%After running this, I receive "Undefined function or variable 'v1.'"
% However, if I write
fsolve(#(v1)i1(v1)-i2(v1),1)
%The function works. With the result, I plugged that value into h(v1), and it produces the expected result (very close to 0)
That said, why doesn't matlab allow me to pass a function handle to fsolve?
You want to pass a function handle, which is h, not h(v1). h(v1) itself can't be evaluated because v1 is not defined.
Try fsolve(h, 1)