Fifth lesson control statements and equations for,while,if Statements and Functions
(1) For loop
V=zeros (10,1)%initial vectors
For I=1:10,%assign for the vectors
V (i) = 2^i;
End
V
(%you can also do:
Indices=1:10;
For I=indices,
V (i) =2^i;
End
V
)
(2) Whileloop
I = 1;
While I <= 5,
V (i) = 100;
I = i+1;
End
V
(3) Break Statememts
I=1;
While true,
V (i) = 999;
I = i+1;
if I = = 6,
Break
End
End
(4) If-else statements
V (1) = 2;
If V (1) = = 1,
Disp (' The value is one. ');
ElseIf V (1) = = 2,
Disp (' The value is. ');
Else
Disp (' The value is not one or both ');
End
(5) Funtions
Example 1 : There is a file named "SQUAREANDCUBETHISNUMBER.M" on the desktop with the following contents:
function [Y1,y2] = Squareandcubethisnumber (x)
y = x^2;
y = x^3;
To call this function, the method is as follows:
(1) enter PWDto see the path of the current file, if not in the same directory as the "SQUARETHISNUMBER.M" file, there are two ways to enter the same directory:
1) Cd/home/flipped/desktop
2) Addpath ('/home/flipped/desktop ')%octave search path (advanced/optional)
(2) call the Squarethisnumber function and enter the following:
Quarethisnumber(5)
As you can see from this example,Octave differs from other languages in that the function can return two and more than two values.
Example 2 : Calculate its cost function from a small number of datasets
There is a file named "COSTFUCTIONJ.M" on the desktop with the following contents:
Unction J = Costfuctionj (X, y, Thera)
m = size (x,1);
predictions = X*thera;
Sqrerrors = (predictions-y). ^2;
J = 1/(2*m) *sum (sqrerrors);
Set X = [1 1;1 2;1 3] (the first column is the x0 value, the second is the value of the sample set x1,x2,x3)
y = [1;2;3] ( The value of y in the sample set)
Thera = [0;1];( Assuming that when x0 is 0 , y is 0,x1 is 1 , y is 1)
The result of running the function is equal to 0. ( if Set Thera = [0,0], the run function result is 2.3333.)
to quantify vectorization
Advantages: (1) using highly optimized algebraic libraries in a variety of languages will make your code run faster and more efficiently. (2) This also means that you can implement some features with less code.
Octave Tutorial ("Machine learning") lesson five "control statements and equations and vectorization"