In [3]:
v = zeros(10, 1);  % Column vector

In [5]:
for i=1:10,    % For i in 1 to 10
   v(i) = 2^i;
end
v


v =

      2
      4
      8
     16
     32
     64
    128
    256
    512
   1024


In [7]:
indexes = 1:10


indexes =

    1    2    3    4    5    6    7    8    9   10


In [9]:
for i=indexes, disp(i), end;


 1
 2
 3
 4
 5
 6
 7
 8
 9
 10

In [11]:
i = 1; 
while i < 5; v(i) = 100; i = i + 1; end;
v


v =

    100
    100
    100
    100
     32
     64
    128
    256
    512
   1024


In [12]:
i = 1;
while true,
    v(i) = 999;
    i = i + 1;
    if i == 6,
        break;
    end;
end;

In [13]:
v(1) = 2;
if v(1) == 1,
    disp('the value is one');
elseif v(1) == 2,
    disp('the value is two');
else
    disp('the value is not one or two');
end;


the value is two

In [14]:
% quit % exit octave

Define a function in a .m file


In [19]:
squareThisNumber(5)  % From squareThisNumber.m


ans =  25

In [20]:
pwd


ans = /home/gary/Devel/python/coursera_ml

In [21]:
% addpath('~/mylibs)  % add search path for modules

Can have functions that return multiple values


In [23]:
[a, b] = squareAndCubeThisNumber(5);
a
b


a =  25
b =  125

In [30]:
X = [1 1; 1 2; 1 3]
y = [1; 2; 3]
theta = [0; 1]


X =

   1   1
   1   2
   1   3

y =

   1
   2
   3

theta =

   0
   1


In [31]:
j = costfunctionJ(X, y, theta)


sqrErrors =

   0
   0
   0

j = 0

In [33]:
theta = [0;0]
j = costfunctionJ(X, y, theta)


theta =

   0
   0

sqrErrors =

   1
   4
   9

j =  2.3333

In [35]:
(1^2 + 2^2 + 3^2) / (2 * 3)  % Validate


ans =  2.3333