matlab编程1 - webdancer's Blog

matlab编程1

webdancer posted @ 2012年4月04日 17:46 in 编程语言 with tags matlab , 1229 阅读

 

数据类型
前面已经学习了matlab编程的主要的数据类型就是矩阵。
介绍其他的一些数据类型:
** multiarrays
例如:rand(2,2,2)
** cellarrays
例如:carr=cell(8,1)
注意:
cellarrays用{}来索引,所以第二个元素为:carr{2}
cellarrays的元素可以使其他类型数据
**字符和文本
例如: str='hello world!'
**结构体
例如:
fp.no=9;
fp.name='torres';
 
控制流
1.条件语句。
if语句
if condition1,
   statement1
elseif condition2,
   statement2
else,
   statement3
end
与C语言的if是一致的,关键词不同,多了一个elseif。
 
switch语句
switch variable
    case constant1,
        statement1
    case constant2,
        statement2,
    otherwise,
        statement3
end
与C语言的switch是不一致的。matlab的switch不是fall through的。第一个case为true,下面的case
不会执行。
注意:在比较两个矩阵时,用isequal函数。
 
例子:
n = floor(real(double(n(1))));

if mod(n,2) == 1
   % Odd order 
   M = oddOrderMagicSquare(n);
elseif mod(n,4) == 0
   % Doubly even order.
   % Doubly even order.
   J = fix(mod(1:n,4)/2);
   K = bsxfun(@eq,J',J);
   M = bsxfun(@plus,(1:n:(n*n))',0:n-1);
   M(K) = n*n+1 - M(K);
else
   % Singly even order.
   p = n/2;   %p is odd.
   M = oddOrderMagicSquare(p);
   M = [M M+2*p^2; M+3*p^2 M+p^2];
   if n == 2
      return
   end
   i = (1:p)';
   k = (n-2)/4;
   j = [1:k (n-k+2):n];
   M([i; i+p],j) = M([i+p; i],j);
   i = k+1;
   j = [1 i];
   M([i; i+p],j) = M([i+p; i],j);
end
2.循环条件。
for语句
for condition,
    statement;
end
 
while语句
while condition,
      statement;
end
还有两个关键字 continue, break。和C语言中的用法是一致的。
 
例子:
二分法解方程x^3-2x-5。
 
a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
   x = (a+b)/2;
   fx = x^3-2*x-5;
   if fx == 0
      break
   elseif sign(fx) == sign(fa)
      a = x; fa = fx;
   else
      b = x; fb = fx;
   end
end
disp(x)
 
try-catch语句
try 
    statement1
catch
    statement2
end
 
语句与java中try-catch类似,try语句块里面有错误发生时,被catch捕获。错误可以用lasterr查看。
 
return语句
结束当前语句,返回到调用函数
 

登录 *


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