matlab教程_台大lecture2

script writing 程序撰写

  1. 保存为.m
    运行:F5  保存时候大小写有区别,字母开头
    注释:% 形成区块:%%(在debug时候很有用),可以分别运行各个部分的内容 

    debug:设置断点,类似于c语言中的,可以看变量的值
    Tips:选中后右键可以智能缩进

structured programming

2.script flow:写程序的一些技巧
script programming:例if elseif for while switch&case break continue end pause return
逻辑符号:类似c语言(~=不等于)

if rem(a, 2) == 0
	disp('a is even');
else
	disp('a is odd');
end
x = 2; k = 0; error = inf;
error_threshold = 1e-32;
while error > error_threshold
    if k > 100
    	break
    end
    x = x - sin(x)/cos(x);
    error = abs(x - pi);
    k = k + 1;
end
for n=1:10
	a(n)=2^n;
end
disp(a)

clear a(否则之前的a的值会影响之后的值)
for n=1:2:10
	a(n)=2^n;
end
disp(a)

>> lecture2
     2     0     8     0    32     0   128     0   512
clear a;
m=1:2:10;
for n=1:length(m)
	a(n)=2^n;
end
disp(a)
去除空格
>> lecture2
     2     4     8    16    32
  1. 为变量预存空间
    可以提升代码运行的速度;否则每次运行都要给变量分配内存地址。

    使用tic toc来计算运行时间
    注意程序运行前要使用

    clear

    来清除影响


%%
clear
tic
for ii = 1:2000
    for jj = 1:2000
        A(ii,jj) = ii + jj;
    end
end
toc

程序输出Elapsed time is 4.616199 seconds.

%%
clear
tic
A = zeros(2000, 2000);		% 预先为变量分配内存空间
for ii = 1:size(A,1)
    for jj = 1:size(A,2)
        A(ii,jj) = ii + jj;
    end
end
toc

程序输出Elapsed time is 2.786401 seconds.

  1. tips:

    clear all:去除之前的变量
    close all:关闭所有的图
    clc:清除命令行的内容
    符号; :不会把执行的结果显示在命令行中
    符号... :换行,把多行语句拼接成一行

    annPoints_sampled = annPoints(annPoints(:,1)>x1 & ...  
    annPoints(:,1) < x2 & ...  
    annPoints(:,2) > y1 & ...  
    annPoints(:,2) < y2);
    

    ctrl C:停止宕机的程序

user-defined function

  1. function:
    内置函数
    eg:>> edit(which('mean.m'))
    可跳转到mean的文件注解  
    
    用户自定义:
    function x = freebody(x0,v0,t)
      % calculation of free falling
      % x0: initial displacement in m
      % v0: initial velocity in m/sec
      % t: the elapsed time in sec
      % x: the depth of falling in m  
      x = x0 + v0.*t + 1/2*9.8*t.*t;  
    

注意这里的.*可以在输入为矩阵时也可以操作

freebody(0, 0, 2)			% 得到 19.6000
freebody(0, 0, [0 1 2 3])	% 得到 [0 4.9000 19.6000 44.1000]  
freebody(0, 0, [0 1; 2 3])	% 得到 [0 4.9000; 19.6000 44.1000]

练习

function FtoC()
%知道华氏温度算摄氏温度
%C=(F-32).*5./9

while 1
   F=input('Temperature in F:');
   if isempty(F)
       break;
   end
   C=(F-32).*5./9;
   final=['Temperature in C:',num2str(C)];
   disp(final);
end

我们也可以使用函数句柄的形式定义函数,这更接近数学上的函数定义,其语法如下:

函数句柄 = @(输入变量) 输出变量
可以直接通过函数句柄调用该方法.

f = @(x) exp(-2*x);  
x = 0:0.1:2;  
plot(x, f(x));
posted @ 2024-03-06 16:40  zzyoctopus  阅读(61)  评论(0)    收藏  举报