help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Pass multiple parameters to a function to use with fminunc


From: Tony Richardson
Subject: Re: Pass multiple parameters to a function to use with fminunc
Date: Fri, 1 May 2020 09:15:17 -0500

On Fri, May 1, 2020 at 8:56 AM Tempo98 <address@hidden> wrote:
I have this function on a .m file:

---------------------------------------------------------
>function [jVal, gradient] = costFunction(theta, m, X, Y)
>  jVal = (1/(2*m)) * sum((X*theta-Y) .^2);
>  gradient = X'*(X*theta-Y);
>endfunction
----------------------------------------------------

and I would like to run it through fminunc in another script that looks like
so:

------------------------------------------------------------------
clear, clc

% loading the data and scaling it
data = ""> mu = mean(data);
dev = std(data);
for i =1:size(data, 2)
  data(:, i) = (data(:, i) - mu(i)) * (1/dev(I));
endfor

% extracting the features (X) and labels from the data (Y)
Y = data(:, end);
X = [ones(size(Y, 1), 1) data(:, [1:end-1])];

% number of training examples (m) and number of features (n)
[m, n] = size(X);

% initializing starting theta vector
iniTheta = zeros(n, 1);

options = optimset('GradObj', 'on', 'MaxIter', 100)

[optTheta, minValue] = fminunc(@costFunction, iniTheta, options)
---------------------------------------------------------------------------------

how can I do so while also passing the m, X and Y parameters?



--
Sent from: https://octave.1599824.n4.nabble.com/Octave-General-f1599825.html

You can define a related anonymous function that  is a function of only one variable, some thing like this:
[optTheta, minValue] = fminunc(@(t) costFunction(t, m, X, Y), iniTheta, options)  

There is another example of this (adapting a function with several parameters to a form that only takes one) in the Anonymous Functions section of the manual.

Tony Richardson

reply via email to

[Prev in Thread] Current Thread [Next in Thread]