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

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.

Related

GNU Octave Script Help - ODE

I'm trying to solve the following ODE:
where R(T) is defined as:
This is my not so great attempt at using Octave:
1;
function xdot = f(t, T)
xdot = 987 * ( 0.0000696 * ( 1 + 0.0038 * ( T(t) - 25 ))) - ( 0.0168 * (T(t)-25 )) - (( 3.25 * 10 ^ (-13))) * ((T(t))^4 - (25^4));
endfunction
[x, istate, msg] = lsode( "f", 100, (t=linspace(0,3600,1000)'));
T_ref and T_infinity_sign are the same constant.
Why isn't my code correct?
If you type
debug_on_error(1)
on your octave session, and then run your code, you will see that the "f" part is called as expected, but then it fails inside lsode with the following error:
error: T(100): out of bound 1 (dimensions are 1x1)
error: called from
f at line 4 column 8
If you look at the documentation of lsode, it says it expects a function f whose first argument is a state vector x, and the second is a scalar, corresponding to time t at which that state vector occurs; f is expected to output the differential dx/dt at time t for state vector x.
From your code it seems that you are reversing the order of the arguments (and their meanings).
Therefore, when you passed T as a second argument to your function, lsode treats it like a scalar, so when you then try to evaluate T(t), it fails with an 'out_of_bounds_ error.
My advice would be, read the documentation of lsode and have a look at its examples carefully, and start playing with it to understand how it works.
PS. The debug_on_error directive launches the debugger if an error occurs during code execution. To exit the debugger type dbquit (or if you're using the GUI, click on the 'Quit Debugging Mode' button at the top right of the octave editor). If you don't know how to use the octave debugger, I recommend you spend some time to learn it, it is a very useful tool.

fsolve error: no function or method found

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.

Index exceeds matrix dimensions on an empty function

I am having this issue with a function that I have created in matlab. I have variables h = 0.2 and x = (0:h:1)'. 'x' is a row vector with 5 elements. I am using the following function in matlab
function d = dplus(fstring, x, h)
d=0;
end
whenever I plug the following into matlab
dplus('prob4Func',x,h)
I get this error "??? Index exceeds matrix dimensions." This makes absolutely no sense since I am not even using the vector 'x' anywhere in the function. Is there some subtlety to matlab I am missing?
I just needed to use 'clearvars dplus' to get it working. Thanks Navan!

(Easy) Matlab: finding zero spots (fzero)

I'm all new to Matlab and I'm supposed to use this function to find all 3 zero spots.
f.m (my file where the function can be found)
function fval = f(x)
% FVAL = F(X), compute the value of a test function in x
fval = exp(-x) - exp(-2*x) + 0.05*x - 0.25;
So obviously I write "type f" to read my function but then I try to do like fzero ('f', 0) and I get the ans 0.4347 and I assume that's 1 of my 3 zero spots but how to find the other 2?
From fzero documentation
x = fzero(fun,x0) tries to find a zero of fun near x0, if x0 is a scalar. fun is a function handle. The value x returned by fzero is near a point where fun changes sign, or NaN if the search fails. In this case, the search terminates when the search interval is expanded until an Inf, NaN, or complex value is found.
So it can't find all zeros by itself, only one! Which one depends on your inputted x0.
Here's an example of how to find some more zeros, if you know the interval. However it just repeatedly calls fzero for different points in the interval (and then still can miss a zero if your discretization is to coarse), a more clever technique will obviously be faster:
http://www.mathworks.nl/support/solutions/en/data/1-19BT9/index.html?product=ML&solution=1-19BT9
As you can see in the documentation and the example above, the proper way for calling fzero is with a function handle (#fun), so in your case:
zero1 = fzero(#f, 0);
From this info you can also see that the actual roots are at 0.434738, 1.47755 and 4.84368. So if you call fzero with 0.4, 1.5 and 4.8 you probably get those values out of it (convergence of fzero depends on which algorithm it uses and what function you feed it).
Just to complement Gunther Struyf's answer: there's a nice function on the file exchange by Stephen Morris called FindRealRoots. This function finds an approximation to all roots of any function on any interval.
It works by approximating the function with a Chebyshev polynomial, and then compute the roots of that polynomial. This obviously only works well with continuous, smooth and otherwise well-behaved functions, but the function you give seems to have those qualities.
You would use this something like so:
%# find approximate roots
R = FindRealRoots(#f, -1, 10, 100);
%# refine all roots thus found
for ii = 1:numel(R)
R(ii) = fzero(#f, R(ii)); end

input element 1 by 1 from other function w/o for loop

I have a function that calculates an array of numbers (randparam) that I want to input element by element into another function that does a simulation.
For example
function [randparam] = arraycode
code
randparam = results of code
% randparam is now a 1x1001 vector.
end
next I want to input randparam 1 by 1 into my simulation function
function simulation
x = constant + constant * randparam + constant
return
end
What makes this difficult for me is because of the return command in the simulation function, it only calculates one step of the equation x above, returns the result into another function, call it integrator, and then the integrator function will call simulation function again to calculate x.
so the integrator function might look like
function integrator (x)
y = simulation(x) * 5
u = y+10
yy = simulation(x) * 10 + u
end
As you can see, integrator function calls the simulation function twice. which creates two problems for me:
If I create a for loop in the simulation function where I input element by element using something like:
for i = 1:100
x = constant + constant * randparam(i) + constant
return
end
then every time my integrator function calls my simulation function again, my for loop starts at 1 all over again.
2.If I some how kept i in my base workspace so that my for loop in my simulation function would know to step up from 1, then my y and yy functions would have different x inputs because as soon as it would be called the second time for yy, then i would now be i+1 thanks to the call due to y.
Is there a way to avoid for loops in this scenario? One potential solution to problem number two is to duplicate the script but with a different name, and have my for loop use a different variable, but that seems rather inefficient.
Hope I made this clear.
thanks.
First, if you generically want to apply the same function to each element of an array and there isn't already a built in vectorized way to do it, you could use arrayfun (although often a simple for loop is faster and more readable):
%# randparam is a 1x1001 vector.
%#next I want to input randparam 1 by 1 into my simulation function
function simulation
x = constant + constant * randparam + constant
return
end
(Note: ask yourself what this function can possibly be doing, since it isn't returning a value and MATLAB doesn't pass by reference.) This is what arrayfun is for: applying a function to each element of an array (or vector, in this case). Again, you should make sure in your case that it makes sense to do this, rather than an explicit loop.
function simulation(input_val)
#% your stuff
end
sim_results = arrayfun( #simulation, randparam);
Of course, the way you've written it, the line
x = constant + constant*randparam + constant;
can (and will) be done vectorized - if you give it a vector or matrix, a vector or matrix will be the result.
Second it seems that you're not clear on the "scope" of function variables in MATLAB. If you call a function, a clean workspace is created. So x from one function isn't automatically available within another function you call. Variables also go out of scope at the end of a function, so using x within a function doesn't change/overwrite a variable x that exists outside that function. And multiple invocations of a function each have their own workspace.
What's wrong with a loop at the integrator level?
function integrator (x)
for i=1:length(x)
y = simulation(x(i)) * 5
u = y+10
yy = simulation(x(i)) * 10 + u
end
And pass your entire randparm into integrator? It's not clear from your question whether you want simulation to return the same value when given the same input, or whether you want it step twice with the same input, or whether you want a fresh input on every call. It is also not clear if simulation keeps any internal state. The way you've written the example, simulation depends only on the input value, not on any previous inputs or outputs, which would make it trivial to vectorize. If we're all missing the boat, please edit your question with more refined example code.