Functions

function [output1,...,outputN] = myfun(input1,...,inputM)

write the following function y=func1(x) as a script file func1.m

Otherwise you may notice the following error message:
Error: Function definitions are not permitted in this context.

$f(x) = x^2 -1$

In [1]:
open func1.m
In [ ]:
function y=func1(x)
    y=x.^2 - 1;
end
In [2]:
func1(2)
ans =

     3
In [3]:
func1([1 2 3])
ans =

     0     3     8
In [4]:
open func2.m
In [ ]:
function [p, q]=func2(x,y)
    p=x.^2+y.^2;
    q=x+y;
end
In [5]:
[p1,q1]=func2(2,3)
p1 =

    13


q1 =

     5
In [6]:
A = [1, 2]; B = [2, 3];
[p2, q2] = func2(A,B)
p2 =

     5    13


q2 =

     3     5
In [7]:
A = [1, 2; 3, 4]; B = [2, 3; 4, 5];
[p3, q3] = func2(A,B)
p3 =

     5    13
    25    41


q3 =

     3     5
     7     9
In [ ]:
function [p, q]=func2(x,y)
    p=x.^2+y.^2;
    q=x+y;
end
In [11]:
phi = @(x, y) x+y;
In [13]:
phi(0,2)
phi([0 1],[2 3])
phi([0 1; 2 3],[2 3;4 5])
ans =

     2


ans =

     2     4


ans =

     2     4
     6     8
In [ ]:
function f = fact(n)
    f = prod(1:n);
end
In [14]:
fact(5)
ans =

   120
In [ ]: