03结构化程式与自定函数

左上角new script新建

for i = 1 : 10

x = linspace(0,10,101);

plot(x,sin(x + i));

print(gcf,'-deps',strcat('plot',num2str(i),'.ps'));

end

layout->command history 查看历史命令

fx寻找方程 选中代码,右键注释,注释使用%,两个%是将代码分区域,可以一个区域一个区域运行

右键smart indent自动缩进

Relational

< <= > >= == ~=(不等于) && ||

rem(a,2) 求a%2

switch case otherwise 每一个case不需要break

prod(1:n) 求n!

tic

for ii = 1:2000

for jj = 1:2000

A(ii,jj) = ii +jj;

end

end

toc

not ptr-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

pre-allocating 运算速度更快

tic和toc计算运行一个程序需要花费多长时间

A = [1 2 3 4 5 6;...

6 5 4 3 2 1]; ...表示换行

当长时间运行一个程序时,ctrl + c可以终止该程序的运行

edit(which('mean.m')) 查看函数

function x = freebody(x0,v0,t)

%

%

%

x = x0 + v0.*t + 1 / 2 * 9.8 * t .* t;

编写函数

function [a F] = acc(v2,v1,t2,t1,m)

a = (v2 - v1) ./ (t2 - t1);

F = m .* a;

%计算加速度和力

[Acc Force] = acc(20,10,5,4,1)

 

function [volume] = pillar(Do,Di,height)

if nargin == 2

height = 1;

end

volume = abs(Do .^ 2 - Di .^ 2) .* height * pi * 4;

nargin 判断输入参数个数

nargout

varargin

varargout     variable length

 

f = @ (x) exp(-2 * x);

x = 0:0.1:2;

plot(x,f(x));

 

input 输入

input('请输入内容')

t = input('请输入内容:','s')

请输入内容123456

ans =123456

请输入内容:9999

t =9999

 

isempty 判断是否为空,bool类型,若为空,返回true

A = ‘ ’

a = isempty (A)

a = 1

 

str=['Alice is ' num2str(12) ' years old!'];

disp(str);

上边这句话也就等价于:

disp=(['Alice is ' num2str(12) ' years old!']);

这就是加中括号的原因,而不是因为num2str(),

因为disp(num2str(12));也是正确的,因为里边就只有一个字符串。

 

语法格式:

  str = num2str(A)

  把数组A中的数转换成字符串表示形式。

  str = num2str(A, precision)

  把数组A转换成字符串形式表示,precision表示精度, 比如precision为3表示保留最多3位有效数字, 例如0.5345转换后为0.534,1.2345转换后为1.23。即从左边第一个不为0的数开始保留3个数值。

  str = num2str(A, format)

  按format指定格式进行格式化转换,通常'%11.4g'是默认的。

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

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值