Functions
File
Create a file squareThisNumber.m which contain the function.
%{
squareThisNumber.m
You can add the function directory to the path with:
addpath('/home/catalin/octave/functions/')
squareThisNumber(5) % ans = 25
%}
function y = squareThisNumber(x)
y = x^2;
%{
squareAndCubeThisNumber.m
Function that returns multiple variables
[a, b] = squareAndCubeThisNumber(5) % a = 25 % b = 125
%}
function [y1, y2] = squareAndCubeThisNumber(x)
y1 = x^2;
y2 = x^3;
Cost function
Define a function to compute the cost function J()
%{
Define a function to compute the cost function J()
X = training examples
y = f(x)
m = number of training examples
h = predictions of hypothesis (m examples)
X = [1 1; 1 2; 1 3]; y = [1; 2; 3]; theta = [0; 1];
j = costFunction(X, y, theta) % j = 0
X = [1 1; 1 2; 1 3]; y = [1; 2; 3]; theta = [0; 0];
j = costFunction(X, y, theta) % j = 2.3333
Manual sanity check
(1/(2*3)) * (1^2 + 2^2 + 3^2)
% ans = 2.3333 % correct
%}
function J = costFunction(X, y, theta)
m = size(X, 1);
h = X*theta;
J = 1/(2*m) * sum((h-y).^2);
Last update: 222 days ago