Why is day() function throwing me this error: Check for missing argument or incorrect argument data type in call to function 'day'? - matlab

Having this long task that I will resume:
Perform a regression model over the normalized active cases in China using the model.....(long assignment that I'm not worried about and will save you time). Tip: To convert from datetime to a numeric variable for the regression, use x=day(date-min(date(:)))+1; being “date” the datetime vector return from getdata function.
This is what I have:
function RP_ejercicio1
data = readtable('COVID-19.csv');
[active_res, confirmed_res, death_res, recovered_res, date] = getdata(data, 'China', 93/147);
x=day(date-min(date(:)))+1;
y = active_res;
yp = log(y./x);
a = [x ones(size(x))];
sol = inv(a'*a)*(a'*yp);
b = sol(1);
c = sol(2);
a = exp(c);
end
I get this error: Check for missing argument or incorrect argument data type in call to function 'day'. In this line: x=day(date-min(date(:)))+1;. The one that is supposed to help as a tip is giving me a headache. I can ensure that date is a 1x50 datetime array after executing the getdata function.
Am I doing something wrong? Is the tip wrong? And if it's the second case, is there other way to do the same?
I add an image for more clarity:
Date array

As somebody said here, you should be using the function days.

Related

Converting DataFrame String column containing missing values to Date in Julia

I'm trying to convert a DataFrame String column to Date format in Julia, but if the column contains missing values an error is produced:
ERROR: MethodError: no method matching Int64(::Missing)
The code I've tried to run (which works for columns with no missing data) is:
df_pp[:tod] = Date.(df_pp[:tod], DateFormat("d/m/y"));
Other lines of code I have tried are:
df_pp[:tod] = Date.(passmissing(df_pp[:tod]), DateFormat("d/m/y"));
df_pp[.!ismissing.(df_pp[:tod]), :tod] = Date.(df_pp[:tod], DateFormat("d/m/y"));
The code relates to a column named tod in a data frame named df_pp. Both the DataFrames & Dates packages have been loaded prior to attempting this.
The passmissing way is
df_pp.tod = passmissing(x->Date(x, DateFormat("d/m/y"))).(df_pp.tod)
What happens here is this: passmissing takes a function, and returns a new function that handles missings (by returning missing). Inside the bracket, in x->Date(x, DateFormat("d/m/y")) I define a new, anonymous function, that calls the Date function with the appropriate DateFormat.
Finally, I use the function returned by passmissing immediately on df_pp.tod, using a . to broadcast along the column.
It's easier to see the syntax if I split it up:
myDate(x) = Date(x, DateFormat("d/m/y"))
Date_accepting_missing = passmissing(myDate)
df_pp[:tod] = Date_accepting_missing.(df_pp[:tod])

Operations with function handle in matlab

Could you please help me with the following issue: I have the following function handle:
r1 = #(lambda) b + lambda*(r - b); % r and b are vectors of return data
I want to find the optimal lambdas that set me a mean function to zero, for a given set of powers within that function. What I tried to do and didn't work, as it returns me an error for undefined operators for input arguments of type 'function_handle' is:
lambda0 = 0.3;
for a = 2:10 %power coefficient
S1(a) = fzero(mean((r - b)*r1.^(1/(a - 1))),lambda0);
end
Any suggestion as to how to go about this problem is highly appreciated! Thank you in advance.
fzero accepts a function handle as the first input. As you currently have it, you're trying to pass a statement as the first input. This statement can't even be properly evaluated because you are trying to perform numerical operations on a function handle (more on this in a bit).
You need to instead do something like this where we create a new function handle that evaluates the original function handle and performs the other operations you need.
S1(a) = fzero(#(lambda)mean((r - b)*r1(lambda).^(1/(a - 1))),lambda0);
Further Explanation
Performing operations on a function handle is not the same as performing them on the result.
So for example, if we had a function handle:
func = #(x)2*x;
If we evaluation this, by calling it with an input value for x
func(2)
4
This works as we would expect. If now we really want the value (2*x)^2, we could try to write it the way that you wrote your statement in your question
func2 = func^2;
We will get an error!
Undefined operator '^' for input arguments of type 'function_handle'.
This does not work because MATLAB attempts to apply the ^ operation to the function handle itself and not the value of the evaluated function handle.
Instead, we would need to create a new function handle that essentially wraps the other one and performs any additional options:
func2 = #(x)func(x)^2;
func2(2)
16
Bringing it Full-Circle
So if we go back to your question, you defined your anonymous function r1 like this.
r1 = #(lambda) b + lambda*(r - b); % r and b are vectors of return data
This all looks great. You have one input argument and you reference r and b from the parent workspace.
Now when you call fzero you try to perform operations on this function handle in hopes of creating a new function handle.
mean((r - b)*r1.^(1/(a - 1)))
Like we just showed this will result in a very similar error
Undefined operator .^ for input arguments of type 'function_handle'
So we need to wrap this into a new function.
newfunc = #(lambda)mean((r - b)*r1(lambda).^(1 / (a - 1)));
Now we can safely pass this to fzero.
result = fzero(newfunc, lambda0);

Save values that are calculated in a function for each iteration of fminsearch

I want to find the Minimum of a function using
[x,fval] = fminsearch(#(param) esm6(param,identi),result(k,1:end-1),options)
now for each Iteration step i want some values that the function 'esm6' calculates to be saved in an Array. I tried the following:
In the first line of the function i wrote
identi.sim.i_optiIter = identi.sim.i_optiIter + 1;
to have an iteration-variable counting the iteration steps of fminsearch. And later to catch the values that I need I used
identi.sim.guete_werte.gew(identi.sim.i_optiIter,:,:) = y_sim;
identi.sim.guete_werte.ungew(identi.sim.i_optiIter,:,:) = y_sim_ungew;
and to make sure that I use the new values of the identi-struct for the next function call, I wrote this at the end of the function:
assignin('base','identi',identi);
Now unfortunatly it doesn't do what I wanted it to do. Can anyone help me with this?
EDIT:
I made another attempt on it, using an Output function. I extendend my Options like this:
options = optimset('Display','iter','MaxIter',3,'OutputFcn',#outfun);
But now the Problem is that i cannot figure out where to put this outfun. The outfun Looks like this:
function stop = outfun(x,optimvalues,state,iteration,y_sim,y_sim_ungew)
stop = false;
if state == 'iter'
guete_werte.gew(iteration,:,:) = y_sim;
guete_werte.ungew(iteration,:,:) = y_sim_ungew;
end
end
Now the Problem with it is, that i can not put it in the file, where i call the fminsearch, because that is a script. If i put the outputfunction into a separate .m-function file, it is not able to Access the variables of the esm6 function. And if I add it to the esm6-function file, matlab can't find the function and says
??? Error using ==> feval Undefined function or method 'outfun' for
input arguments of type 'struct'.

What is "index should be positive integer(not complex format integer)" in MATLAB?

// I made function like this:
function y = ZL(L,f)
if isvector(f)
y=1j*2*pi.*f*L;
else
y=1j*2*pi.*f*L;
end
// and command :
L = 10,
f= -10000:100:10000,
ZL=ZL(L,f);
// then error :
index should be positive integer(not complex format integer) or boolean
-> this error is translated by me who is Korean; sorry
what's wrong with it?
First time you call ZL = ZL(L,f), you don't get any error.
If you try to call your command a second time, you'll get this error: Index exceeds matrix dimensions. It's because you affect the variable ZL, so the second time it's not the function you're calling but you"re trying to get elements from the array ZL.
So please don't use same name for a variable and an existing function, otherwise the function name is masked by the variable.

Passing a variable out of local functions

I'm having some trouble with local functions within my code so I've pasted a simple example below:
function [avg,testvar] = test(x) %Warning
n = length(x);
avg = mymean(x,n);
end
function [a,testvar] = mymean(v,n)
a = sum(v)/n;
testvar=123;
end
One can probably see what I'm attempting; to pass testvar out of the local functions. However Matlab returns the warning:
"The function return value 'testvar' might be unset"
with respect to the line I've commented "%Warning".
What's the best way of getting around this?
You need to specify the value of the second output of test(). Otherwise how can MATLAB know what its value is supposed to be? It doesn't know the second output of mymean() should be routed to the second output of test(). Perhaps this will solve your problem.
function [avg,testvar] = test(x) %Warning
n = length(x);
[avg, testvar] = mymean(x,n);
end
function [a,testvar] = mymean(v,n)
a = sum(v)/n;
testvar=123;
end
The variables between brackets after function are the output variables.
In your first function, you did not assign any value to testvar hence the warning. If you add testvar = 123; in the first function, the warning goes away. Or you can remove testvar from the output variables, leaving:
function avg = test(x)