calling a matlab function whose name contains a numeric variable - matlab

I have a set of functions such that I want to apply each of them in a separate iteration. I label the functions as: Strategy1(x), Strategy2(x)....Strategy100(x). As you can see, there is a numeric variable in the name of the function. I want to achieve something like
LS = [Strategy1(x),Strategy2(x),...,Strategy100(x)];
Y = zeros(100,1);
for i = 1:1:100
Y(i) = Strategyi(x);
end
I wonder if there is a way to achieve this goal in matlab?

You could create function handles by using str2func
n = 100;
Y = zeros(n,1);
for i = 1:n
funcH = str2func( sprintf('Strategy%d', i));
Y(i) = funcH(x);
end
If you want to concatenate the function names outside the for loop you could use srtcat
strcat('Strategy', strread( num2str(1:n), '%s'))

Related

Function handle as input to the function handle

Is it possible in Matlab to create function handle that will take as input another function handle and how?
e.g. I have h = #(x) x^2
I want to have h as parameter and get as output function that 4*x^2
function alpha = fun(h, type)
x= sym('x',[8,1]);
gamma = 16;
alpha_ = gamma*h(x);
alpha = matlabFunction(alpha_, 'vars', {x});
end
Is it possible to create something like that? I want to avoid creating alphas for multiple function handles.

Body of this Matlab function works, but not the function itself (interp1 error)

I've written the following piece of subcode (with parameters commented) for an Euler policy iteration algorithm. When I try to run the body of the function (everything below global) for say, a1 = 1, it works, and returns a scalar. However, when I call the function as euler_diff_test(1), I get an error. (Pasted below)
function diff = euler_diff_test(a1)
%the following comments are example parameters. They are in the global line originally.
% r = 0.2, a = 0.5, y = 1.1, a_grid = linspace(0.5,7,100)
%policy_guess = zeros(2,N);
%policy_guess(1,:) = 0.3*a_grid;
%policy_guess(2,:) = 0.3*a_grid;
% M = zeros(2,2); %M for markov transition kernel
% M(1,1) = p;
% M(2,2) = p;
% M(2,1) = 1-p;
% M(1,2) = 1-p;
% j = 1
global r a y a_grid policy_guess M j;
c = (1+r)*a + y - a1; %consumption formula
if c<=1e-02 %don't care about consumption being negative
diff = 888888888888888888888;
else
policy_func = interp1(a_grid', policy_guess', a1, 'linear');
diff = 1/c - beta*(1+r)*(1 ./ policy_func)*M(j,:)';
end
end
Error Reads:
Any help is much appreciated!
The problem is that you dont understand globals nor how they work!
You seem to be doing something like:
N=100; p=0.1;
r = 0.2, a = 0.5, y = 1.1, a_grid = linspace(0.5,7,100)
policy_guess = zeros(2,N);
policy_guess(1,:) = 0.3*a_grid;
policy_guess(2,:) = 0.3*a_grid;
M = zeros(2,2); %M for markov transition kernel
M(1,1) = p;
M(2,2) = p;
M(2,1) = 1-p;
M(1,2) = 1-p;
euler_diff_test(1)
And this is causing the error you show. Of course it is!
First, you need to learn what a global is and what worskpaces are. Each fucntion has its own worskpace or "scope". That means that only variables defined within the workspace are visible by the function itself.
A global variable is one that exist for all workspaces, and everyone can modify it. You seem to want all those variables defined outside the function, inside your function. But realise! when the variables are defined, they are not global. The function starts, and in its first line, it does only know about the existence of a1. Then, later, you define a bunch of variables as global, that the function did not know about. So what does the function do? just create them empty, for you.
If you want your the variables that you create in the main script scope to be global, you need to declare them as global then, not inside the function. So cut your line global ... from the fucntion, and put it on top of the script where you declare all your variables, i.e. on top of
% here!
N=100; p=0.1;
...
in my example.
Now, the important stuff: Global variables are bad. When you have globals, you don't know who modifies, and its super easy to lost track of what is happening to them, because every function that uses a variable a will modify the global a, so its a pain to debug. Almost no one uses globals because of this. The best way is to pass them to the function as input, i.e. define your function as:
function diff = euler_diff_test(a1,r, a, y, a_grid, policy_guess, M, j)

How to change a script to a function?

I've got a set of data in an excel sheet that I've imported onto MATLAB however there are NaNs within that set of data. I've figured out some code in the main script to replace the NaN's into the wanted values:
max = x(:, 2);
min = x(:, 3);
for j = 1:length(max)
for k = 1:length(min)
if isnan (max(j))
max (j) = ((max(j-1)+max(j+1))/2);
elseif isnan (min(k))
min (k) = ((min(k-1)+min(k+1))/2);
end
end
end
However, I need to be able to turn this code into a user-defined function and call it from the main script instead of having all the calculations on the main script.
I've tried to start making the function:
function [missingmax, missingmin] = missing(max, min)
However, I could not figure the rest out.
function [max_x, min_x] = missing(x)
max_x = x(:, 2);
min_x = x(:, 3);
for jj = 1:length(max_x)
for kk = 1:length(min_x)
if isnan (max_x(jj))
max_x (jj) = ((max_x(jj-1)+max_x(jj+1))/2);
elseif isnan (min_x(kk))
min_x (kk) = ((min_x(kk-1)+min_x(kk+1))/2);
end
end
end
end
You were on the right track. Couple of things:
Your input is x, not min,max
Your outputs are min and max, not missingmax and missingmin
j denotes the imaginary unit It's not recommended for use as a variable, hence I changed it.
You called variables min and max. Don't do that. Ever. Seriously. Don't. If you manage to do min=4 and then try to calculate the minimum of an array, you'll get a bunch of errors. Basically: never use the name of a build-in function for a variable.
Since you do a linear interpolation, you don't need to define a function here. It already exists in Matlab : fillmissing
So you can replace missing values in x like that
x_filled = fillmissing(x,'linear')

Fill matrix with function values in Matlab

I've got 3 functions, oe1(n), oe2(n) and oe3(n).
I want to create a matrix representing the function values.
The structure of the matrix should be like this:
A = [oe1(0) oe2(0) oe3(0); oe1(1) oe2(1) od3(1); ...... ; oe1(N-1), oe2(N-1), oe3(N-1)];
I've tried filling it with a for loop, but it does not work.
Is there a standard Matlab operation for this? I really can't figure out how to do it.
Anders.
oe1(n1) = sin(2*pi*F*n1+phi)
oe2(n1) = ones(length(n1),1);
oe3(n1) = n1*Ts
pol = (oe2)'
vector_x = [a; b; c];
vector_veardier = [oe1(n1), 1, oe3(n1)]
xi = 1:N-1;
for i = 2:N-1;
for j = 1:3
vector_veardier(i, j) = oe1(j);
end
end
Do your functions accept vectors? If so you can use:
A = [oe1((1:N)'), oe2((1:N)'), oe3((1:N)')];
but otherwise you might have to use arrayfun:
A = [arrayfun(#oe1, (1:N)'), arrayfun(#oe2, (1:N)'), arrayfun(#oe3, (1:N)')];
Note that in your provided code you have not defined oeN as functions, but as some kind of array with a value inserted at position n1.
One way to do it with a for loop would however be:
A = zeros(N,3);
for i = 1:N,
A(i,:) = [oe1(i), oe2(i) oe3(i)];
end

Building a vector of multiple structure values in MATLAB

I'm trying to create a function that reads in a field of a structure to create a vector of fields. I have a structure of the form:
subject(i).stride(j).strideLength
and there are 10 subjects, about 10 strides per subject. I can create a long vector of the strideLength of all subjects, all strides with code like this:
k = 1;
for i=1:10
for j=1:size(subject(i).stride, 2)
varVector(k) = subject(i).stride(j).strideLength;
k = k + 1;
end
end
however, there are a lot of different fields I want to do this with, and I'd like to do it with a function that I can call like this:
x(1) = groupData(strideLength);
but I can't figure out the syntax to append strideLength to subject(i).stride(j). within the above loop in a function. This is what I hoped would work and didn't:
function [varVector] = groupData(var)
%groupData returns a concatenated vector of a given variable (speed, etc.)
k = 1;
for i=1:10
for j=1:size(subject(i).stride, 2)
varVector(k) = subject(i).stride(j).var;
k = k + 1;
end
end
end
Any thoughts on how to do this right? Thanks in advance!
In your groupData function, pass in the field/variable name as a string
x(1) = groupData('strideLength');
Then in the body of the code, access this field as follows
varVector(k) = subject(i).stride(j).(var);
Try the above and see what happens!