吴恩达机器学习5-5(控制语句)

for循环

>> v=zeros(10,1)
v =

   0
   0
   0
   0
   0
   0
   0
   0
   0
   0

>> for i=1:10,
v(i)=2^i;
end;
>> v
v =

      2
      4
      8
     16
     32
     64
    128
    256
    512
   1024

>>

for循环更为 简单的写法

>> indices = 1:10;
>> indices
indices =

    1    2    3    4    5    6    7    8    9   10

>>

while循环

>> i = 1
i =  1
>> while i < 5,
v(i)=100;
i = i+1;
end;
>> v
v =

   100
   100
   100
   100
     0
     0
     0
     0
     0
     0

>>

条件语句

>> 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
>>

新建函数

新建一个文本文件squareThisNumber.m

编写

function y = squareThisNumber(x)

y = x^2;

然后在文件路径打开Octave,直接可以运行

squareThisNumber(5)

函数返回多个值

function [y1,y2] = squareAndCubeThisNumber(x)

y1 = x^2;
y2 = x^3;

执行

>> [a,b] = squareAndCubeThisNumber(5)
a =  25
b =  125
>>

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×