matlab编程2 - webdancer's Blog

matlab编程2

webdancer posted @ 2012年4月05日 02:54 in 编程语言 with tags matlab , 1146 阅读

matlab里面记录代码的文件成为M-files。可以分为两种类型:script和function。

1.script。不接受输入,也不返回输出。它对workspace的数据进行操作。和python等的脚本文件是一样的,把在控制台的命令给保存起来。

2.function。接受输入参数,返回输出。这类文件的一个注意的地方就是文件名和函数名必须相同.

例子:

function r = rank(A,tol)
%RANK   Matrix rank.
%   RANK(A) provides an estimate of the number of linearly
%   independent rows or columns of a matrix A.
%   RANK(A,tol) is the number of singular values of A
%   that are larger than tol.
%   RANK(A) uses the default tol = max(size(A)) * eps(norm(A)).
%
%   Class support for input A:
%      float: double, single

%   Copyright 1984-2007 The MathWorks, Inc.
%   $Revision: 5.11.4.5 $  $Date: 2007/08/03 21:26:23 $

s = svd(A);
if nargin==1
   tol = max(size(A)) * eps(max(s));
end
r = sum(s > tol);

从这个例子中,看出:

1.从第一行看出,文件名与函数名一致。

2.%的行为注释,用help rank可以查看(当然,help方法删掉了一些没用的,比如最后两行)。

3.下面为函数体,是函数的实现。参数的参数数目可以用方法nargin和nargout获得。(n/arg/in)

function可以分为以下几种类型:

1.匿名函数。

不用创建专门的m文件,可在命令行,m文件内部创建。语法如下

f=@(arglist) expression

例子:

>> sqrt=@(x) x.^(1/2);

2.主函数和子函数。

函数类型的M文件需要一个主函数,放在第一位;后面可以跟若干个子函数(当然可以不跟)。

3.私有函数。

只对一些函数可见,放在名称为:private的目录下面。

4.嵌套函数。

在函数体内,定义新的函数。

提示:

构造字符串参数

用[]可以连接字符串,很容易来构造所需要的参数。

例子:

for i=1:10,
    s=['index' int2str(i) '.dat'];
    load(s);
end 

特殊的函数:

eval:可以执行matlab命令。

例子:

>> cmd='1+1';
>> eval(cmd)

函数句柄:

使用@符号,可以获得matlab函数的句柄。这通常在把matlab函数作为参数的时候非常有用。

function [f,g] = myfun(x)
f = 3*x(1)^2 + 2*x(1)*x(2) + x(2)^2;    % Cost function
if nargout > 1
   g(1) = 6*x(1)+2*x(2);
   g(2) = 2*x(1)+2*x(2);
end

options = optimset('GradObj','on');
x0 = [1,1];
[x,fval] = fminunc(@myfun,x0,options);

使用矩阵运算代替迭代。

在matlab中矩阵运算都经过优化,速度较快。

 


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter
Host by is-Programmer.com | Power by Chito 1.3.3 beta | © 2007 LinuxGem | Design by Matthew "Agent Spork" McGee