MATLAB--结构化程式与自定义函数

一、结构化程式

1、逻辑运算符

运算符作用
<小于
<=小于或等于
大于
>=大于或等于
==等于
~=不等于
&&

2、流程控制语句以及示例

流程控制语句作用
if若if语句为真,则执行子句
switch根据switch语句内容判断执行哪个子句
while重复执行子句直到while中的条件为假
for执行子句固定次数

①if语句

if condition1
     statement1;
elseif condition2
     statement2;
else
     statement3;
end

if语句示例1

if rem(a,2)==0
    disp('a is even');
else
    disp('a is odd');
end

运行结果: a is odd

②switch语句

switch expression
case value1
     statement1;
case value2
     statement2;
……
otherwise
     statement;
end

switch语句示例:2

switch input_num
case -1
	disp('negative 1');
case 0
	disp('zero');
case 1
	disp('positive 1');
otherwise
	disp('other value');
end

运行结果:other value

③while语句

while expression
     statement;
end
n = 1;
while prod(1:n) < 1e100    //prod函数用于求数组元素的乘积
	n = n + 1;
end

运行结果: n=70

④for语句

for variable=start:increment:end
     commands;
end
for n=1:10
	a(n)=2^n;
end
disp(a)
      2           4           8          16          32          64         128         256         512        1024

★上述所有循环和条件语句都要在末尾以end闭合

⑤break语句

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

3、为变量预分配空间(pre-allocating space to variables)

①NOT pre-allocating

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

程序结果:时间已过 3.754662 秒。

②Pre-allocating

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

程序结果:时间已过 0.038823 秒。

程序一比程序二所用的时间更长.这是因为: 对于程序一,没有预先为变量A分配内存,因此每当A的形状发生改变时,都需要重新为A分配内存地址,这花费了更多的时间。

二、函数(Funtions)

1、查看内置函数

edit(which('mean.m'))

在matlab中看到mean的源代码如下:
在这里插入图片描述

2、撰写函数

①自由落体

在这里插入图片描述

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)			
freebody(0, 0, [0 1 2 3])	
freebody(0, 0, [0 1; 2 3])	

得到 19.6000
得到 [0 4.9000 19.6000 44.1000]
得到 [0 4.9000; 19.6000 44.1000]

②bubblesort算法

图1.bubblesort算法代码运行
在这里插入图片描述运行结果
在这里插入图片描述

③判断闰年

判断闰年程序
在这里插入图片描述

运行程序
在这里插入图片描述运行程序结果
在这里插入图片描述

④华氏温度到摄氏温度的转换

function F2C()
while 1
    F_degree = input('tempreature in Fahrenheit: ', 's');
    F_degree = str2num(F_degree);
    if isempty(F_degree)
        return
    end
    C_degree = (F_degree-32)*5/9;
    disp(['tempreature in Celsius: ' num2str(C_degree)])
end

这里是引用


  1. 命令行输入a=5 ↩︎

  2. 命令行输入:input_num=5 ↩︎

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值