第二周 第五部分

循环

>> 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
>> indices=1:10;
>> indices
indices =

    1    2    3    4    5    6    7    8    9   10

>> for i =indices,
>      disp(i);%空格不重要
>  end;
 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
while
>> i=1;
>> while i<=5,
>    v(i)=100;
>    i=i+1;
>  end;

>> v
v =

    100
    100
    100
    100
    100
     64
    128
    256
    512
   1024
>> i=1;
>> while true,
>    v(i)=999;
>    i=i+1;
>    if i==6,
>       break;
>    end;%要有end
>  end;
>> v
v =

    999
    999
    999
    999
    999
     64
    128
    256
    512
   1024
>> v(1)
ans =  999
>> 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 error');
>  end;
The value is two
exit 或者 quit 可以退出Octave
调用函数:
创建一个文件,以你的函数来命名(后缀名 .m)。进入文件的目录再调用函数才可以
如:square.m
 function y = square(x)
 y =x^2;
>> pwd
ans = E:dasandedasiokafterdeep learningmaterial
>> square(3)
ans =  9
在C:UsersclttDesktop保存一个文件f.m
function y =f(x),
y = x+3;
>> addpath('C:UsersclttDesktop')%添加Octave 的寻找路径
>> pwd
ans = E:dasandedasiokafterdeep learningmaterial
>> f(2)%即使不再f.m的目录下,此时依然可以调用函数f
ans =  5
 
现在对square.m进行更改
function [y1,y2] = square(x)%返回多个值
 y1 =x^2;
 y2 = x^3;

>> pwd
ans = E:dasandedasiokafterdeep learningmaterial
>> [a,b] = square(5);
>> a
a =  25
>> b
b =  125
>> X = [1 1;2 2;3 3]
X =

   1   1
   2   2
   3   3

>> Y =[1;2;3]
Y =

   1
   2
   3

>> thera = [0;1]
thera =

   0
   1
cosf.m
function J =cosf(X,Y,thera),
m =size(X,1);
predictions = X*thera;
sqrerrors = (predictions-Y).^2;%用.^表示^
J = 1/(2*m) *sum(sqrerrors);
>> J = cosf(X,Y,thera)
J = 0%完美拟合

改变thera
>> thera = [0;0];
>> J = cosf(X,Y,thera)
J =  2.3333
(1^2+2^2+3^2)/(2*3)=7/3

 向量化

%点乘
>> v =[1;2;3];
>> w =[1;2;3];
>> v.*w
ans =

   1
   4
   9

>> sum(v.*w)
ans =  14
>>

>> A =magic(3)
A =

   8   1   6
   3   5   7
   4   9   2

>> B = A^2 %A*A
B =

   91   67   67


   67   91   67
   67   67   91

>> B = A.^2
B = 64 1 36 9 25 49 16 81 4 >> B = A.*2 B = 16 2 12 6 10 14 8 18 4 >> B = A*2 B = 16 2 12 6 10 14 8 18 4
原文地址:https://www.cnblogs.com/tingtin/p/12040656.html