Matlab "Index exceeds the number of array elements." error - matlab

I have this matlab code, and it it supposed to take user input of a function, a limit, and threshold error. Then it uses the formula |f(n) - L| < error, and counts how many iterations of n is needed in order to hold that formula true. this is my code, but I keep getting this error:
Warning: Too many FOR loop iterations. Stopping after 9223372036854775806 iterations.
In untitled (line 13)
Index exceeds the number of array elements. Index must not exceed 2.
Error in untitled (line 14)
if (abs(f(n) - L) <= err)
This is my code:
prompt = "input a function: ";
f = input(prompt,"s");
prompt = "input a limit: ";
L = input(prompt);
prompt = "input the error threshold: ";
err = input(prompt);
for n = 1:inf
if (abs(f(n) - L) <= err)
break;
end
end
disp(n)
I tried figuring out what the problem is, but I am not really sure, if anyone could help me understand, that would be great.

Related

"Unable to prove literally" error when trying to create a symbolic function based on an existing function

I need to find inverse of virtual value function of lognormal random variables. This is what I tried to do:
syms flogn(x,p1,p2)
% assume(p2<=0); %Adding this doesn't change the error
flogn(x,p1,p2) = x - logncdf(x,p1,p2,'upper')/lognpdf(x,p1,p2);
glogn = finverse(flogn,x);
But I got the error:
Error using symengine
Unable to prove 'p2 <= 0' literally. Use 'isAlways' to test the statement mathematically.
Error in sym/subsindex (line 810)
X = find(mupadmex('symobj::logical',A.s,9)) - 1;
Error in sym/privsubsasgn (line 1085)
L_tilde2 = builtin('subsasgn',L_tilde,struct('type','()','subs',{varargin}),R_tilde);
Error in sym/subsasgn (line 922)
C = privsubsasgn(L,R,inds{:});
Error in logncdf>locallogncdf (line 73)
sigma(sigma <= 0) = NaN;
Error in logncdf (line 47)
[varargout{1:max(1,nargout)}] = locallogncdf(uflag,x,varargin{:});
Error in Untitled5 (line 3)
flogn(x,p1,p2) = x - logncdf(x,p1,p2,'upper')/lognpdf(x,p1,p2);
I also tried with beta distribution, and got a similar error. How can I use logncdf with symbolic variables?
Note that you could have minimalize your sample code even more, like this:
syms flogn(x,p1,p2)
flogn(x,p1,p2) = logncdf(x,p1,p2);
It's shorter, produces the same error and helps us to focus on the source of the error message.
So, the error doesn't come from trying to inverse a function, but from trying to use an existing function for numerical calculations with symbolic variables.
The error comes from the fact that you want to create a symbolic function flogn based on existing function logncdf, and logncdf has a multiple comparisons.
With the command edit logncdf, you can read the source code of the function and see comparison at lines 73 and 76.
% Return NaN for out of range parameters.
sigma(sigma <= 0) = NaN;
% Negative data would create complex values, which erfc cannot handle.
x(x < 0) = 0;
Matlab cannot compare symbols so it throws errors.
Depending on what you really need, you can have different solutions.
Do you really need to symbolize the function flogn? Couldn't you just write it as a function then calculate the inverse of it (if it can be inversed...)?
If you really want to keep the symbolization, you can also rewrite your own function logncdf (with another name) so it does not have the comparisons. But it's still not guaranteed that you will find an inverse.

Matlab Black Scholes formula how to get volatility from B&S price

I'm quite beginning with matlab and have a question maybe simple ?
i got Black&Scholes formula to get a call option price with the following input parameters :
S = stock price, K = strike , r = rate, T = time to expiration , sigma = volatility
Call option price is given by :
C(S,K,r,t,sigma) = S *N(d1) - K e^-rT *N(d2)
d1 = (1/sqrt(T))*(ln(S/K)+(r+0.5*sigma^2)*T)
d2 = d1 - sigma*sqrt(T)
I have no probleme with this function but i need to get the black scholes volatility.
I have as inputs : S, K , r , T , BlackScholesPrice and i want to return sigma.
I tried with "syms sig; solve ("blackscholesequation"==blacksholesprice, sig);" but there's nothing to do, i always get an error
"Error using symfun>validateArgNames (line 211)
Second input must be a scalar or vector of unique symbolic variables.
Error in symfun (line 45)
y.vars = validateArgNames(inputs);
Error in sym/subsasgn (line 762)
C = symfun(B,[inds{:}]);
Error in normcdf>localnormcdf (line 100)
p(sigma==0 & x<mu) = 0;
Error in normcdf (line 46)
[varargout{1:max(1,nargout)}] = localnormcdf(uflag,x,varargin{:});
Error in BlackScholesInverse (line 3)
solve(S0*normcdf((log(S0/K)+(r+0.5*sig*sig)*T)*(1/(sig*sqrt(T))))-K*exp(-r*T)*normcdf((log(S0/K)+(r+0.5*sig*sig)*T)*(1/(sig*sqrt(T)))-sig*sqrt(T))==
prixBS,sig)"
If anybody got an idea it would be awesome. Thx all'
You are trying to find implied volatility. For that you can use blsimpv. It would be easier to use this function, just that you need to give the inputs according.

error in fmincon Matlab

`
function [LLF, LL, H ] = garchlike(data)
p=1;
q=1;
if isempty(q)
m=p;
else
m = max(p,q);
end
%this are the parameters
psi=[0.01;0.01];
gamma=[0;0.02;0.02;0];
lambda=[0;0.03;0.03;0];
A=[1;-0.04;-0.03;1];
stdestimate = std(data,1);
data = [stdestimate ; data];
T = size(data,1);
B=(reshape(A,2,2))^-1;
%I am squaring each element of the inverse of A
B2=((reshape(A,2,2))^-1).^2;
%getting the Bl matrix(squared interactions)
Bl=[B2(1,:);B(1,:).*B(2,:);B2(2,:)];
garchc=Bl*psi;
garcha=Bl*(reshape(gamma,2,2))*reshape(A.^2,2,2);
garchb= Bl*(reshape(lambda,2,2))*reshape(A.^2,2,2);
H(1,1).day=[0.001; 0; 0; 0.002; ];
%convert to matrix
H(1,1).day=ivech(H(1,1).day);
for t = (m + 1):T
H(1,t).day= ivech(garchc + garcha*(diag(H(1,t-1).day))+ garchb*(data((t-1),:).^2)');
end
% Getting the loglikelihood
LLF=zeros(1,T);
%the loklikelihood
for t = (m + 2):T
LLF(t)= log(det(H(1,t).day))+ data(t,:)/(H(1,t).day)*data(t,:)';
end
t=(m+2):T;
LLF=-LLF(t);
LL=sum(LLF);
`
I have this function from up and trying to minimize using fmincon:
` [parameters,LLF,EXITFLAG, OUTPUT,HESSIAN] = fmincon('garchlike', [psi;gamma;lambda;A],sumA ,sumB ,[] , [] , LB , UB,[],options, data, p , q);`
I don't know why is not working and gives me an error :
"Error using garchlike
Error using garchlike
Too many input arguments.
Error in fmincon (line 631)
initVals.f = feval(funfcn{3},X,varargin{:});
Caused by:
Failure in initial user-supplied objective function evaluation. FMINCON cannot continue."
"Error using garchlike Too many input arguments." is your problem.
fmincon is calling garchlike([psi;gamma;lambda;A],data, p , q), but your garchlike only takes 1 argument.
Pro tip: learn how to use the debugger. Start by setting dbstop if error.
EDIT: okay, here are some more details. Please read carefully.
Your garchlike takes 1 argument as input, while your fmincon is calling it with 4 arguments.
Either (1) you need to remove those 3 extra arguments (namely, data, p, q) from fmincon, or (2) make garchlike take 3 more arguments!!

"Unable to prove `expr` literally..." error when trying to compare a symbol inside a function

I just started learning MATLAB and I'm trying to normalize a bump function given by
function b = bump(x)
region1 = abs(x) < 1
b(region1) = (exp(-1./(1 - x(region1).^2)))
region2 = abs(x) >= 1
b(region2) = 0
end
To do this, I need to divide by the definite integral from -1 to 1. However, when I input
syms x;
int(bump(x), -1, 1)
I get a long error message, which says
Error using symengine (line 58)
Unable to prove 'abs(x) < 1' literally. To test the statement mathematically, use isAlways.
Error in sym/subsindex (line 1554)
X = find(mupadmex('symobj::logical',A.s,9)) - 1;
Error in sym>privformat (line 2357)
x = subsindex(x)+1;
Error in sym/subsref (line 1578)
[inds{k},refs{k}] = privformat(inds{k});
Error in bump (line 3)
b(region1) = (exp(-1./(1 - x(region1).^2)))
I tried replacing abs(x)<1 with what I think is the suggested isAlways(abs(x)<1), and that removes the error, although it gives the wrong answer (it says the integral is zero).
I don't understand what does the error message means.
syms x defines x as a symbolic variable, invoking symbolic computation on x. This probably isn't what you want.
Instead, define x as some kind of input matrix, e.g. x = zeros(3);. Or, to do numeric integration, use the integral function:
integral(#bump, -1, 1)

matlab cant divide using /

I have some simple function that takes in a value
This value is the checked off a number of if or elseif statements to calculate another value.
The problem is it seems to find an error when trying to run which says
Error using /
Matrix dimensions must agree.
Error in abc (line 9)
a = 5000 / g;
the code is as follows
function abc(g)
if (g == 100)
a = 1;
elseif (g <= 99 & g >= 50)
a = 200 -2*g;
elseif (g <= 50 & g >= 1)
a = 5000 / g;
else
warning('Invalid value passed, a defaults to 1');
a =1;
end
end
So, im passing in abc 100 and i expect a to be 1 but instead it runs through each if / elseif and throws an error on a = 5000/g
I should also mention that i initially tried using && in the elseifs but this also gave an error which said
Operands to the || and && operators must be convertible to logical scalar values.
Error in abc (line 6)
elseif (g <= 99 && g >= 50)
Anybody any idea whats going on here ?
Thanks
You are probably passing a matrix to your function, e.g. when you call
abc(yourdata)
yourdata is actually not one number, but a matrix. If you called directly
abc(100)
you should not see your problem (or do you?).
In other words, your main problem is not inside your function, but when you call it!
Given your description, it seems that you set yourdata(1) to the value 100 that you want to test, but some other element of the matrix has a different value, which is why the if construct branches into the else case. There, you need ./ instead of / if you want to do element-wise division instead of matrix division.
But really you probably just need to make sure that yourdata is scalar when you call your function.