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

主要内容:

1.script writing 脚本编写

2.structured programming 结构化程序设计

3.structured programming 用户定义函数

一.部分基础操作(脚本编辑器script editor)

新建脚本

for i=1:10
    x=linspace(0,10,101);
    plot(x,sin(x+i));
    print(gcf,'-deps',strcat('plot',num2str(i),'.ps'));
end

1.程序内一部分不运行

当想让程序内某一行不运行,可以在该行前加符号%,即可将改行变为注解,该行不运行

若想让程序内连续几行不运行,可以将该部分选中,右击选择【注释】,或点击工具栏内【注释】按键

2.程序继续运行:

若想让选中程序继续运行,可选中该部分程序,右击或者在工具栏中单击【取消注释】即可

3.运行部分代码:可用来检测程序的bug,分部分进来检查

在该部分代码前输入%%,即可将代码进行分节,单击选中需要运行部分,点击工具栏内【运行节】按键,即可运行该部分代码

单击【运行或F5】按键,运行整个程序

4.查看程序到某一节点前是否存在错误:

点击第四行,4右侧横线,变为圆点,(中断点)

代表代码在运行到第4行时,就会停止,此时可以查看已执行程序是否符合预期或存在错误

退出:关掉中断点,点击上侧工具栏【继续】按键,即可退出

5.当输入代码未缩进,可全选【ctrl+A】,右击,选择【智能缩进】

二.层次码执行

按照行的顺序,从上到下

更改条件之后,再次输出结果时,需要先清除之前输出的变量

structured programming(结构化程序设计)

if,elseif,else   

if  condition1
    statement1
elseif condition2
      statement2
else
      statement3
end

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

rem,表示remainder余数

even,表示even number偶数

odd,表示odd number奇数

disp,表示display显示

for

for用来执行一个事情很多次(遍历循环)

for variable=start:increment(增量):end

     commands

end

for n=1:10
    a(n)=2^n;
end
disp(a)

依次输出2^n,直至2^10

i=1
for n=1:2:10
    a(i)=2^n;
    i=i+1
end
disp(a)

依次输出2的奇数次方,直至n到10

switch,case

switch expression(表达式)

case value 1

          statement1

case value 2

        statement2

...

otherwise

       statement

end

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

otherwise

try,catch

while

(条件循环)

while expression

         statement

end

n=1;
while prod(1:n)<1e100
    n=n+1;
end

prod相乘

prod(1:n)=prod([1 2 3...n])=1*2*3...*n=n!

e100=10^100(10的100次方)

break(与while一起用)

continue

end

pause

return

relational(logical)   operators   关系(逻辑)操作符

<   

<=

>

>=

== equal to

~= not equal to 不等于

&& and

||  or

三.pre-allocating space to variables 为变量预分配空间

为变量预分配空间可以大大减少代码的运算时间

例:未分配

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

历时 1.565193 秒

例:分配

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

历时 0.021914 秒

tic指令,用来计时

四.一些小Tips

1.【clear all】消除之前的所有变量

2.【close all】关掉所有图形

3.【clc】清空【命令行窗口】

4.使用分号【】,不会将所有的运行结果都显示在【命令行窗口】,可使页面保持干净

5.【...】换行号      接续上一行

6.【Ctrl+C】在程序执行中,即界面右下角显示busy,可协助跳出程序

五.MATLAB内置函数的内容

1.【>>edit(which('mean.m'))

funtion---keyword关键字

y---output输出

mean---function name=file name函数名

x---input输入

绿色输出---online help

再往下---MATLAB Code

2.定义函数,进行调用

function x=freebody(x0,v0,t)
x=x0+v0+1/2*9.8*t.*t;

注意点乘

即,定义了freebody函数

将此保存至以freebody命名的对应的文件下

在【命令行窗口】即可以调用此函数

>>freebody(0,0,10)    ans=490

即初始位置与初始时间均为0,经过10s之后,自由落体运动经过的路程

3.定义acc函数

function[a,F]=acc(v2,v1,t2,t1,m)
a=(v2-v1)./(t2-t1);
F=m.*a;

acc=acceleration加速度

4.

nargin---number of function input arguments函数输入参数的个数

nargout---函数输出参数的个数

varargin---variable length input argement list    可变长度输入参数列表

varargout---可变长度输出参数列表

inputname---variable name of function input   函数输入的变量名

mfilename---file name of currently running function   当前运行函数的文件名

5.function handles函数句柄

a way to create anonymous functions

一种创建匿名函数的方式

f=@(x) exp(-2*x);
x=0:0.1:2;
plot(x,f(x));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
``` <!DOCTYPE html> <html> <head> <title></title> </head> <style> * { padding: 0; margin: 0; } html, body { height: 100%; padding: 0; margin: 0; background: #000; } canvas { position: absolute; width: 100%; height: 100%; } .aa { position: fixed; left: 50%; bottom: 10px; color: #ccc; } </style> <body> <canvas id="pinkboard"></canvas> <script> /* * Settings */ var settings = { particles: { length: 500, // maximum amount of particles duration: 2, // particle duration in sec velocity: 100, // particle velocity in pixels/sec effect: -0.75, // play with this for a nice effect size: 30 // particle size in pixels } }; /* * RequestAnimationFrame polyfill by Erik M?ller */ (function () { var b = 0; var c = ["ms", "moz", "webkit", "o"]; for (var a = 0; a < c.length && !window.requestAnimationFrame; ++a) { window.requestAnimationFrame = window[c[a] + "RequestAnimationFrame"]; window.cancelAnimationFrame = window[c[a] + "CancelAnimationFrame"] || window[c[a] + "CancelRequestAnimationFrame"]; } if (!window.requestAnimationFrame) { window.requestAnimationFrame = function (h, e) { var d = new Date().getTime(); var f = Math.max(0, 16 - (d - b)); var g = window.setTimeout(function () { h(d + f); }, f); b = d + f; return g; }; } if (!window.cancelAnimationFrame) { window.cancelAnimationFrame = function (d) { clearTimeout(d); }; } })(); /* * Point class */ var Point = (function () { function Point(x, y) { this.x = typeof x !== "undefined" ? x : 0; this.y = typeof y !== "undefined" ? y : 0; } Point.prototype.clone = function () { return new Point(this.x, this.y); }; Point.prototype.length = function (length) { if (typeof length == "undefined") return Math.sqrt(this.x * this.x + this.y * this.y); this.normalize(); this.x *= length; this.y *= length; return this; }; Point.prototype.normalize = function () { var length = this.length(); this.x /= length; this.y /= length; return this; }; return Point; })(); /* * Particle class */ var Particle = (function () { function Particle() { this.position = new Point(); this.velocity = new Point(); this.acceleration = new Point(); this.age = 0; } Particle.prototype.initialize = function (x, y, dx, dy) { this.position.x = x; this.position.y = y; this.velocity.x = dx; this.velocity.y = dy; this.acceleration.x = dx * settings.particles.effect; this.acceleration.y = dy * settings.particles.effect; this.age = 0; }; Particle.prototype.update = function (deltaTime) { this.position.x += this.velocity.x * deltaTime; this.position.y += this.velocity.y * deltaTime; this.velocity.x += this.acceleration.x * deltaTime; this.velocity.y += this.acceleration.y * deltaTime; this.age += deltaTime; }; Particle.prototype.draw = function (context, image) { function ease(t) { return --t * t * t + 1; } var size = image.width * ease(this.age / settings.particles.duration); context.globalAlpha = 1 - this.age / settings.particles.duration; context.drawImage( image, this.position.x - size / 2, this.position.y - size / 2, size, size ); }; return Particle; })(); /* * ParticlePool class */ var ParticlePool = (function () { var particles, firstActive = 0, firstFree = 0, duration = settings.particles.duration; function ParticlePool(length) { // create and populate particle pool particles = new Array(length); for (var i = 0; i < particles.length; i++) particles[i] = new Particle(); } ParticlePool.prototype.add = function (x, y, dx, dy) { particles[firstFree].initialize(x, y, dx, dy); // handle circular queue firstFree++; if (firstFree == particles.length) firstFree = 0; if (firstActive == firstFree) firstActive++; if (firstActive == particles.length) firstActive = 0; }; ParticlePool.prototype.update = function (deltaTime) { var i; // update active particles if (firstActive < firstFree) { for (i = firstActive; i < firstFree; i++) particles[i].update(deltaTime); } if (firstFree < firstActive) { for (i = firstActive; i < particles.length; i++) particles[i].update(deltaTime); for (i = 0; i < firstFree; i++) particles[i].update(deltaTime); } // remove inactive particles while ( particles[firstActive].age >= duration && firstActive != firstFree ) { firstActive++; if (firstActive == particles.length) firstActive = 0; } }; ParticlePool.prototype.draw = function (context, image) { // draw active particles if (firstActive < firstFree) { for (i = firstActive; i < firstFree; i++) particles[i].draw(context, image); } if (firstFree < firstActive) { for (i = firstActive; i < particles.length; i++) particles[i].draw(context, image); for (i = 0; i < firstFree; i++) particles[i].draw(context, image); } }; return ParticlePool; })(); /* * Putting it all together */ (function (canvas) { var context = canvas.getContext("2d"), particles = new ParticlePool(settings.particles.length), particleRate = settings.particles.length / settings.particles.duration, // particles/sec time; // get point on heart with -PI <= t <= PI function pointOnHeart(t) { return new Point( 160 * Math.pow(Math.sin(t), 3), 130 * Math.cos(t) - 50 * Math.cos(2 * t) - 20 * Math.cos(3 * t) - 10 * Math.cos(4 * t) + 25 ); } // creating the particle image using a dummy canvas var image = (function () { var canvas = document.createElement("canvas"), context = canvas.getContext("2d"); canvas.width = settings.particles.size; canvas.height = settings.particles.size; // helper function to create the path function to(t) { var point = pointOnHeart(t); point.x = settings.particles.size / 2 + (point.x * settings.particles.size) / 350; point.y = settings.particles.size / 2 - (point.y * settings.particles.size) / 350; return point; } // create the path context.beginPath(); var t = -Math.PI; var point = to(t); context.moveTo(point.x, point.y); while (t < Math.PI) { t += 0.01; // baby steps! point = to(t); context.lineTo(point.x, point.y); } context.closePath(); // create the fill context.fillStyle = "#ea80b0"; context.fill(); // create the image var image = new Image(); image.src = canvas.toDataURL(); return image; })(); // render that thing! function render() { // next animation frame requestAnimationFrame(render); // update time var newTime = new Date().getTime() / 1000, deltaTime = newTime - (time || newTime); time = newTime; // clear canvas context.clearRect(0, 0, canvas.width, canvas.height); // create new particles var amount = particleRate * deltaTime; for (var i = 0; i < amount; i++) { var pos = pointOnHeart(Math.PI - 2 * Math.PI * Math.random()); var dir = pos.clone().length(settings.particles.velocity); particles.add( canvas.width / 2 + pos.x, canvas.height / 2 - pos.y, dir.x, -dir.y ); } // update and draw particles particles.update(deltaTime); particles.draw(context, image); } // handle (re-)sizing of the canvas function onResize() { canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight; } window.onresize = onResize; // delay rendering bootstrap setTimeout(function () { onResize(); render(); }, 10); })(document.getElementById("pinkboard")); </script> </body> </html> ``` ![示例图片](https://devbit-static.oss-cn-beijing.aliyuncs.com/devbit-static/img/heart.png)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值