fsolve error: no function or method found - octave

I wrote this code in octave:
syms z;
f=z-2;
fsolve("f",0.)
Then this gives the error
#f: no function and no method found.
Also using fsolve(#f,0) gives the same error
When I write code as:
syms z;
f=z-2;
fsolve(f,0.)
Then this gives the error
ind2sub: subscript indices must be either positive integers less than 2^31 or logicals.
Please explain to me how to actually use fsolve.

% syms z; % Not needed, actually slows down the code
f=#(z)(z-2);
fsolve(f,0.)
You're missing the # symbol, which is a function handle. This tells Octave that f is not a variable, but actually is a(n anonymous) function, in this case of z, which is the first argument.
You'll probably want to have z to be a regular variable, because making it symbolic turns MATLAB from a speeding race car to a drudging farm vehicle. Unless there's a specific reason to have z symbolic (I cant think of any in case of usage with fsolve)' it's best to avoid symbolic maths.

Related

Can I define a maxima function f(x) which assigns to the argument x

Sorry for the basic question, but it's quite hard to find too much discussion on Maxima specifics.
I'm trying to learn some Maxima and wanted to use something like
x:2
x+=2
which as far as I can tell doesn't exist in Maxima. Then I discovered that I can define my own operators as infix operators, so I tried doing
infix("+=");
"+=" (a,b):= a:(a+b);
However this doesn't work, as if I first set x:1 then try calling x+=2, the function returns 3, but if I check the value of x I see it hasn't changed.
Is there a way to achieve what I was trying to do in Maxima? Could anyone explain why the definition I gave fails?
Thanks!
The problem with your implementation is that there is too much and too little evaluation -- the += function doesn't see the symbol x so it doesn't know to what variable to assign the result, and the left-hand side of an assignment isn't evaluated, so += thinks it is assigning to a, not x.
Here's one way to get the right amount of evaluation. ::= defines a macro, which is just a function which quotes its arguments, and for which the return value is evaluated again. buildq is a substitution function which quotes the expression into which you are substituting. So the combination of ::= and buildq here is to construct the x: x + 2 expression and then evaluate it.
(%i1) infix ("+=") $
(%i2) "+="(a, b) ::= buildq ([a, b], a: a + b) $
(%i3) x: 100 $
(%i4) macroexpand (x += 1);
(%o4) x : x + 1
(%i5) x += 1;
(%o5) 101
(%i6) x;
(%o6) 101
(%i7) x += 1;
(%o7) 102
(%i8) x;
(%o8) 102
So it is certainly possible to do so, if you want to do that. But may I suggest maybe you don't need it? Modifying a variable makes it harder to keep track, mentally, what is going on. A programming policy such as one-time assignment can make it easier for the programmer to understand the program. This is part of a general approach called functional programming; perhaps you can take a look at that. Maxima has various features which make it possible to use functional programming, although you are not required to use them.

In octave, error: for x^A, A must be a square matrix. Use .^ for elementwise power

In Octave I defined a function in a separate file square.m
function y = square(x)
y = x^2;
endfunction
In other file script.m I have
disp("Hello World 2");
fplot( #(x) square(x),[-1 1])
And I get
error: for x^A, A must be a square matrix. Use .^ for elementwise power.
Also if I try
y = x.^2;
inside the function I get the exact same message
The reason you're getting that error is because fplot is passing the range you specified all at once as a vector, treating your function as a vectorised function, expecting a vector input and returning a vector output.
You can confirm this by turning "debug on error" to true, by doing debug_on_error(true), run the offending line, and inspect x.
Therefore, inside your function, things go wrong, because you're trying to get the square of a vector, which is an illegal operation (mathematically speaking).
Converting your function to y = x.^2 should work in this case, because you'd be converting each element of the vector to its square, which is what you want. But obviously, simply changing ^ to .^ might not work for every problem.
In general, it's better to create your own 'range' and 'outputs' and plot them directly using plot; this gives you far more control, and you can inspect the inputs and outputs first to ensure you're plotting what you think you're plotting.
Welcome to StackOverflow!
I have just tried your code on https://octave-online.net/ (no need to create an account nor even the files).
The second version works "as expected": y = x .^ 2; inside the function.
Make sure you saved the file after the modification?

error: 'y' undefined near line 8 column 12 error: called from computeCost at line 8 column 3

error: 'y' undefined near line 8 column 12
error: called from computeCost at line 8 column 3
Here is my code:
1;
function J = computeCost(X, y, theta)
%COMPUTECOST Compute cost for linear regression
% J = COMPUTECOST(X, y, theta) computes the cost of using theta as the
% parameter for linear regression to fit the data points in X and y
% Initialize some useful values
m = length(y); % number of training examples
% You need to return the following variables correctly
J = 0;
% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta
% You should set J to the cost.
J = sum(( X * theta - y ) .^2 )/( 2 * m );
% =========================================================================
end
I am guessing it's an error from Coursera ML course assignment. I think you are trying to run the file which contains the implementation of function computeCost(X, y, theta), not the file which calls the computeCost(,,) function with values of X, y, theta. This is why you are getting the error as you aren't providing y.
Run the file which is calling computeCost() function, not the file which contains the implementation of computeCost() function.
That is:
For Week2 Assignment 1: Run ex1.m file
For Week3 Assignment 2: Run ex2.m file
There are two things happening here. First you are defining your function dynamically as opposed to in its own file; not sure why you would prefer that.
Second, after having defined this computeCost function, you are calling it from a context where you did not pass a y argument (or presumably, you didn't pass any arguments to it, and y happens to be the first one detected as missing inside the function).
Since this is a cost function and your code looks suspiciously like code from Andrew Ng's Machine Learning course on Coursera, I am going to go out on a limb here and guess that you called computeCost from something else that was supposed to use it as a cost function to be optimised, e.g. fminunc. Typically functions like fminunc expect a function handle as an argument, but they expect a very specific function handle too. If you look at the help of fminunc, it states that:
FCN should accept a vector (array) defining the unknown variables,
and return the objective function value, optionally with gradient.
Therefore, if you want to pass a function that is to be computed with three arguments, you need to "wrap" it into your own handle, which you can define on the spot, e.g. #(x) computeCost(x, y, t) (assuming 'y' and 't' exist already).
So, I'm guessing that instead of calling fminunc like so: fminunc( #(x) computeCost(x, y, t),
you probably called it like so: fminunc( #computeCost )
or even like so: fminunc( computeCost ) (which evaluates the function first, rather than pass a function handle as an argument).
Basically, go back to the code given to you by coursera, or read the notes carefully. You're calling things the wrong way.
Actually, you are trying to run a function and you can't run it until you provide the desired no. of parameters. Doing so, you may encounter the following error:
computeCost error: 'y' undefined near line 7 column 12
error: called from computeCost at line 7 column 3
As you see, here I'm calling this function without passing any argument.
SOLUTION:
You can test your code by running 'ex1' script. After that submit your work by calling 'submit' script.

Scilab fsolve returning incorrect argument (error 98)

I am trying to run fsolve to resolve a dissociation equation but I keep getting this error. I tracked it down to the x(1)^(1/2) term (removing the square root yields no error) but I can't find a way to solve the proper equation I need. The code is below.
T = 2000
Kp = exp(-deltaG/(Ru*T))
function [f]=func(x)
f(1) = 2-x(1)*4 / (3*x(1) - 1)*(x(1))^(1/2) - Kp
endfunction
x0 = [1]
[x,f_x] = fsolve(x0,func)
EDIT: More requested info
The error is
!--error 98 variable returned by scilab argument function is
incorrect
Ru is the gas constant, 8.315.
DeltaG is -135643.
Kp is 3.489e-3.
This is a book example, x should yield 0.3334.
What kind of solved this problem was that I updated scilab to version 6.0.1 from 5.5. The problem is that depending on the initial guess x0 the values of x get really absurd and x0 has to be so close to the real answer that it defeats the purpose of the calculation.
Also I don't have access to Maple, my other alternative would be MATLAB
Using symbolic calculus software like xcas or Maple one can solve your equation symbolycally
There are 3 solutions:
s1=((1/4)*t1+(1/4)*(Kp-2)^2/t1-(1/4)*Kp+1/2)^2
s2=(-(1/8)*t1-(1/8)*(Kp-2)^2/t1-(1/4)*Kp+1/2+(1/2*%i)*sqrt(3)*((1/4)*t1-(1/4)*(Kp-2)^2/t1))^2
s3=(-(1/8)*t1-(1/8)*(Kp-2)^2/t1-(1/4)*Kp+1/2-(1/2*%i)*sqrt(3)*((1/4)*t1-(1/4)*(Kp-2)^2/t1))^2
where
t=sqrt(-Kp*(Kp-4)*(Kp-2)^2)
t1=(-(Kp-2)*(Kp-2*sqrt(2))*(Kp+2*sqrt(2))+4*t)^(1/3);
depending on Kp values some solutions can be complex.

Defining mathematical functions with summation in Octave

I want to define the mathematical function sum(x^z)+z where x ranges from 1:10 and z is a variable
One way I tried is
syms z
f=#(z)(z)
for i=1:10
f=f+(i.^z)
end
But this leads to a error: binary operator '+' not implemented for 'function handle' by 'matrix' operations
I also tried to define a function initially of two variables x and z as
syms x
syms z
f(x,z)=z+(x.^z)
sum(f([1:10,z]))
It also gives error
Please tell me the correct method to do this.