MATLAB学习笔记2——结构化程序及自定义函数

杂记

注解与分块

Comment:%
Section:%%

逻辑运算符

Not equal to: ~=
And: &&
Or: ||

disp(variable):display the value of a variable(can be a string)

Pre-allocating

%A
for n = 1:10
	a(n) = 2^n
end
disp(a)
	
%B
a = zeros(1,10)
for n = 1:10
	a(n) = 2^n
end
disp(a)	

In A example,we do not pre-allocate space to vector a rather than letting MATLAB resize it on every iteration.
B runs faster than A

计时

tic
commands
toc

其他

  • clear variable/all : to remove variable(s)
  • close all : to close all figures
  • clc : 清空命令行窗口
  • … : 换行
  • ctrl + C : 强行停止程序运行

各种结构(加end)

if elseif else

if condition1
	statement1
elseif condition2
	statement2
else condition3	
	statement3
end			

switch

switch expression
case value1
	statement1
case value2
	statement2
otherwise
	statement
end	

由expression得到的value对应一个case,运行那个case下的语句

while

while condition 
	statement
end

break continue

for

for variable=start:increment:end
	commands
end	

函数

内置函数

查看内置函数的代码

edit(which('function.m'))

nargin, nargout, varargin, varargout

  • nargin/nargin(‘function name’):函数输入参数个数
  • nargout/nargout(‘function name’):函数输出参数个数
    详细介绍

自定义函数(脚本名要与函数名相同)

例:自由落体运动的路程
f = x 0 + v 0 t + 1 / 2 g t 2 f = x_0+v_0t+1/2gt^2 f=x0+v0t+1/2gt2

function y = freebody(x0, v0, t) % 输出多个变量时:function [a f] = ...
% calculation of free falling
% x0: initial displacment in m
% ...
y = x0 + v0.*t + 1/2 *9.8 *t.*t;
% *,/必须用.*, ./在使用矩阵计算的时候会发挥用处

在这里插入图片描述

函数句柄(匿名函数)

f = @(x) exp(-2*x)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值