This is the code, it just calculates two outputs based on two inputs x and y.
function [nextX, nextY]=newton(x,y)
nextX= x-((6*(x^2)*(y^2)*(x+y)-9*(y^2)((y^3)+14)-2*(x^2)*(5*(x^2)-69))/(x*y*(18*x*y+20)));
nextY= y-((10*(x^4)+18*x^2*(y^3)-414*(x^2)+30*x*(y^2)-420*x)/(x*y*(18*x*y+20)));
end
[x,y]=newton(1,1)
I get
error: newton: A(I): index out of bounds; value 15 out of bound 1
error: called from:
error: newton at line 2, column 6
whenever I try to run it, I'm a novice at octave and I really can't see what I'm doing wrong here.
You have a very simple error (probably a typo) in your code here:
nextX= x-((6*(x^2)*(y^2)*(x+y)-9*(y^2)((y^3)+14)-2*(x^2)*(5*(x^2)-69))/(x*y*(18*x*y+20)));
^
There is no operator between two parentheses, so Octave assumes that you're trying to get an element of a vector/matrix by it's index, thus throwing index out of bounds exception.
Probably you wanted to multiply two values instead:
nextX= x-((6*(x^2)*(y^2)*(x+y)-9*(y^2)*((y^3)+14)-2*(x^2)*(5*(x^2)-69))/(x*y*(18*x*y+20)));
Related
I am using RANSAC to fit a line to my data. The data is 30X2 double, I have used MatLab example to write the code given below, but I am getting an error in my problem. I don't understand the error and unable to resolve it.
The link to Matlab example is
https://se.mathworks.com/help/vision/ref/ransac.html
load linedata
data = [xm,ym];
N = length(xm); % number of data points
sampleSize = 2; % number of points to sample per trial
maxDistance = 2; % max allowable distance for inliers
fitLineFcn = polyfit(xm,ym,1); % fit function using polyfit
evalLineFcn =#(model) sum(ym - polyval(fitLineFcn, xm).^2,2); % distance evaluation function
[modelRANSAC, inlierIdx] = ransac(data,fitLineFcn,evalLineFcn,sampleSize,maxDistance);
The error is as follows
Error using ransac Expected fitFun to be one of these types:
function_handle
Instead its type was double.
Error in ransac>parseInputs (line 202) validateattributes(fitFun,
{'function_handle'}, {'scalar'}, mfilename, 'fitFun');
Error in ransac (line 148) [params, funcs] = parseInputs(data, fitFun,
distFun, sampleSize, ...
Lets read the error message and the documentation, as they tend to have all the information required to solve the issue!
Error using ransac Expected fitFun to be one of these types:
function_handle
Instead its type was double.
Hum, interesting. If you read the docs (which is always the first thing you should do) you see that fitFun is the second input. The error says its double, but it should be function_handle. This is easy to verify, indeed firLineFun is double!
But why? Well, lets read more documentation, right? polyfit says that it returns an array of the coefficient values, not a function_hanlde, so indeed everything the documentation says and the error says is clear about why you get the error.
Now, what do you want to do? It seems that you want to use polyfit as the function to fit with ransac. So we need to make it a function. According to the docs, fitFun has to be of the form fitFun(data), so we just do that, create a function_handle for this;
fitLineFcn=#(data)polyfit(data(:,1),data(:,2),1);
And magic! It works!
Lesson to learn: read the error text you provide, and the documentation1, all the information is there. In fact, I have never used ransac, its just reading the docs that led me to this answer.
1- In fact, programmers tend to reply with the now practically a meme: RTFM often, as it is always the first step on everything programming.
Program (programmatically implement) the problem of solving the rigid equation eq = -lambda * (y-sin (x)) using the ode45 solver in the Octave environment.
There is code
lambda=10#Global variable for function
function slv=fi(x)#Equation solution
C=1+(lambda/(1+pow2(lambda)));
slv=C*exp(-lambda*x)-(lambda/(1+pow2(lambda)))*(-lambda*sin(x)+cos(x));
end
#The initial function of the equation
function y=g(t,x)
y=-lambda*(x-sin(t));–1 ERROR
end
%Determination of parameters for controlling the course of the equation
optio=odeset("RelTol",1e-5,"AbsTol",1e-5,'InitialStep',0.025,'MaxStep',0.1);
[XX,YY]=ode45(#g,[0 0.25],2,optio); - 2 ERROR
#Exact solution
x1=0:0.05:0.25;
y1=fi(x1);
%Function solution graph with ode45 and exact solution
plot(x1,y1,'-g:exact solution;',XX,YY,'*b;ode45;');
grid on;
But there are some errors:
lambda = 10
error: 'lambda' undefined near line 11, column 11
error: called from
g at line 11 column 4
runge_kutta_45_dorpri at line 103 column 12
integrate_adaptive at line 135 column 39
ode45 at line 241 column 12
LabWork6 at line 18 column 8
Due to the lambda variable in the function, the error moved to another part of the program.
What did I do wrong when declaring a lambda?
Variables at 'global' scope in a script are not visible from within functions, even if defined on the command-line instead of their own file, as it the proper way.
This makes sense if you think about it, because command-line functions are just convenience syntax, and a file-defined function would have no idea that some other script defines a variable somewhere, unless you use the global keyword to tell it about that variable.
So either declare lambda as global both outside and inside your function, or simply wrap your entire script inside a function, which then allows 'nested' functions to see/inherit parent-function variables.
I have a function where I want to solve for many variables separately, do I have to write down the function every time in terms of the other variable?
x,xG,xR
y = e.^tan(x.^2)+cos.^2(x);
yG = e.^tan(xG.^2)+cos.^2(xG);
First you cannot write an expression like cos.^2(x). If x is a single variable (ie x=pi) you could write either cos(x)^2 or cos(x^2). If x is a vector (a column vector might be x=[3;4;pi] and a row vector might be x=[3,4,pi], then you might write cos(x).^2 or cos(x.^2). The role of the period (.) in octave is explained here: https://octave.org/doc/v4.0.3/Arithmetic-Ops.html
Another issue has to do with understanding the difference between an expression: x=e^tanh(y); and a function. The later is a separate chunk of code that can be invoked from anywhere in your program.
Consider this simple example
1;
function y=myfunc(x)
y=exp(tanh(x));
endfunction
## main program
xxx=pi/3;
yyy=myfunc(xxx);
printf('%7.3f %7.3f\n',xxx,yyy)
y=exp(tanh(pi/3))
comments: The '1' in the first line tells Octave that there is more to the script than just the following function: the main program has to be interpreted as well. The function line specifies that inside the function, the input will be called x and the output y, so when my function is called from main, the input is xxx(=pi/2) and the output is yyy. The last line in this tiny script is an expression that does the same thing as the function. Note that since I didn't include a semi-colon at the end of that line the result is printed out
I suggest you play with this for a while, then if you have more questions, ask them in a new question.
I'm working with Octave4.2.1 and I have written this function (in the file OctaveFunction.m):
function y = squareNumber(x)
y = x^2;
endfunction
but if I call the function, I get this error:
error: 'squareNumber' undefined near line 1 column 1
and if I try to call the function in this way:
OctaveFunction squareNumber(4)
I get another error:
warning: function name 'squareNumber' does not agree with function filename 'C:\Users\HOME\Desktop\OctaveFunction.m'
error: for x^A, A must be a square matrix. Use .^ for elementwise power.
error: called from
OctaveFunction at line 2 column 7
Where did I go wrong? Thank you!
I think the main problem is that your file name does not match the function name. If you were to match these, this should resolve your first error.
Regarding the elementwise power error: If given the proper input (4) this should not lead to an error, as 4 is obviously a square matrix.
Hence it seems that some undesired input is fed to your function, but again this problem is likely to disappear if you rename the file to match the functionname, and call the function as usual. (so without OctaveFunction).
You Must rename your file such as your function name
for example: your file name is (main.m) and your function name is (main)
I have the following issue:
I want to use autowrap to generate a compiled version of a sympy matrix, with cells containing sympy expressions. Depending on the specification of my problem, the number of arguments can get very large.
I ran into the following 2 issues:
The number of arguments that autowrap accepts seems to be limited to 509.
i.e., this works:
import sympy
from sympy.utilities.autowrap import autowrap
x = sympy.symbols("x:509")
exp = sum(x)
cyt = autowrap(exp, backend="cython", args=x)
and this fails to compile:
x = sympy.symbols("x:510")
exp = sum(x)
cyt = autowrap(exp, backend="cython", args=x)
The message I get seems not very telling:
[...] (Full output upon request)
Generating code
c:\users\[classified]\appdata\local\temp\tmp2zer8vfe_sympy_compile\wrapper_module_17.c(6293) : fatal error C1001: An internal error has occurred in the compiler.
(compiler file 'f:\dd\vctools\compiler\utc\src\p2\hash.c', line 884)
To work around this problem, try simplifying or changing the program near the locations listed above.
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information
LINK : fatal error LNK1257: code generation failed
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1257
Is there any way around this? I would like to use versions of my program that need ~1000 input variables.
(I have no understanding of C/cython. Is this an autowrap limitation, a C limitation ...?)
Partly connected to the above:
Can one compile functions that accept the arguments as array.
Is there any way to generate code that accepts a numpy array as input? I specifically mean one array for all the arguments, instead of providing the arguments as list. (Similar to lambdify using a DeferredVector). ufuncify supports array input, but as I understand only for broadcasting/vectorizing the function.
I would hope that an array as argument could circumvent the first problem above, which is most pressing for me. Apart from that, I would prefer array input anyways, both because it seems faster (no need to unpack the numpy array I have as input into a list), and also more straightforward and natural.
Does anyone have any suggestions what I can do?
Also, could anyone tell me whether f2py has similar limitations? This would also be an option for me if feasible, but I don't have it set up to work currently, and would prefer to know whether it helps at all before investing the time.
Thanks!
Edit:
I played around a bit with the different candidates for telling autowrap that the input argument will be something in array form, rather than a list of numbers. I'll document my steps here for posterity, and also to increase chances to get some input:
sympy.DeferredVector
Is what I use with lambdify for the same purpose, so I thought to give it a try. However, warning:
A = sympy.DeferredVector("A")
expression = A[0]+A[1]
cyt = autowrap(expression, backend="cython", args=A)
just completely crashed my OS - last statement started executing, (no feedback), everything got really slow, then no more reactions. (Can only speculate, perhaps it has to do with the fact that A has no shape information, which does not seem to bother lambdify, but might be a problem here. Anyways, seems not the right way to go.)
All sorts of array-type objects filled with the symbols in the expression to be wrapped.
e.g.
x0 ,x1 = sympy.symbols("x:2")
expression = x0 + x1
cyt = autowrap(expression, backend="cython", args=np.array([x0,x1]))
Still wants unpacked arguments. Replacing the last row by
cyt = autowrap(expression, backend="cython", args=[np.array([x0,x1])])
Gives the message
CodeGenArgumentListError: ("Argument list didn't specify: x0, x1 ", [InputArgument(x0), InputArgument(x1)])
Which is a recurrent theme to this approach: also happens when using a sympy matrix, a tuple, and so on inside the arguments list.
sympy.IndexedBase
This is actually used in the autowrap examples; however, in a (to me) inintuitive way, using an equation as the expression to be wrapped. Also, the way it is used there seems not really feasible to me: The expression I want to cythonize is a matrix, but its cells are themselves longish expressions, which I cannot obtain via index operations.
The upside is that I got a minimal example to work:
X = sympy.IndexedBase("X",shape=(1,1))
expression = 2*X[0,0]
cyt = autowrap(expression, backend="cython", args=[X])
actually compiles, and the resulting function correctly evaluates - when passed a 2d-np.array.
So this seems the most promising avenue, even though further extensions to this approach I keep trying fail.
For example this
X = sympy.IndexedBase("X",shape=(1,))
expression = 2*X[0]
cyt = autowrap(expression, backend="cython", args=[X])
gets me
[...]\site-packages\sympy\printing\codeprinter.py", line 258, in _get_expression_indices " rhs indices in %s" % expr)
ValueError: lhs indices must match non-dummy rhs indices in 2*X[0]
even though I don't see how it should be different from the working one above.
Same error message when sticking to two dimensions, but increasing the size of X:
X = sympy.IndexedBase("X",shape=(2,2))
expression = 2*X[0,0]+X[0,1]+X[1,0]+X[1,1]
cyt = autowrap(expression, backend="cython", args=[X])
ValueError: lhs indices must match non-dummy rhs indices in 2*X[0, 0] + X[0, 1] + X[1, 0] + X[1, 1]
I tried snooping around the code for autowrap, but I feel a bit lost there...
So I'm still searching for a solution and happy for any input.
Passing the argument as an array seems to work OK
x = sympy.MatrixSymbol('x', 520, 1)
exp = 0
for i in range(x.shape[0]):
exp += x[i]
cyt = autowrap(exp, backend='cython')
arr = np.random.randn(520, 1)
cyt(arr)
Out[48]: -42.59735861021934
arr.sum()
Out[49]: -42.597358610219345