吴恩达机器学习_42控制语句

一、for 语句

>> v=zeros(10,1) %生成一个10*1的零矩阵

v =
     0
     0
     0
     0
     0
     0
     0
     0
     0
     0

>> for i=1:10,    %i从1循环到10
     v(i) = 2^i;
   end;
>> v

v =
           2
           4
           8
          16
          32
          64
         128
         256
         512
        1024

 二、 indices(索引)

indices 可以代替for语句进行循环。

>  indices=1:10;    %设置索引为1-10
>> indices

indices =
     1     2     3     4     5     6     7     8     9    10        %可以看到indices为1-10
>> for i = indices,   %和i=1:10相同
    disp(i);
 end;
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10

 三、while和if语句

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

>> v

v =

       999
       999
       999
       999
       999
       64
       128
       256
       512
       1024

四、if-else语句

>> 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 is not one or two.');
   end;
The value
is two

五、如何定义和调用函数

首先需要建立一个以(函数名.m)为名的文件,最好使用写字板打开该文件,防止代码格式混乱。

注意:函数文件必须放在MATLAB的路径中,才会被识别。(pwd命令:查看当前的路径,cd命令:更改路径)

addpath命令可以增加自定义路径,使其被MATLAB接受。

六、定义一个函数且返回多个值

function [y1,y2] = squareandcubethisnumber(x)
y1
=x^2; y2=x^3;
>> [a,b]=squareandcubethisnumber(5) a = 25 b = 125

七、一个具体的例子

function J = costfunctionj(X,y,theta)
%X is the 'design matrix' containing our training examples.X是包含我们训练示例的设计矩阵
%y is the class labels

m= size(X,1);    % number of  training examples 训练样本的数量
predictions = X*theta    % predictions of hypothesis on all m examples
sqrErrors = (predictions-y).^2;    % squared errors 平方差,(A.^B):计算 A 中每个元素的B次方
J = 1/(2*m) * sum(sqrErrors);    %求代价函数J

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

X =

1 1
1 2
1 3

>> y=[1;2;3]

y =

1
2
3

>> theta = [0;1];
>> j= costfunctionj(X,y,theta)

predictions =

1
2
3


j =

0

原文地址:https://www.cnblogs.com/vzyk/p/11503157.html