一个以MATLAB制作的动态扇子

来源:互联网 发布:安东尼生涯数据 编辑:程序博客网 时间:2024/05/17 07:00

:::[下载源文件]:::


气温在这5月份上升显著,夏季来临前总是这个样子。对卖家电的来说,空调肯定是这季节的一大财政来源。我们都知道,虽然空调比风扇凉快,但更费电。现在人们都流行讲环保,我们也应该尽量少开空调,这样即节能又省钱。

在这篇文章里,我将展示一个用MATLAB制作的GIF动态扇子,希望能为大家消消暑,这样有可能风扇也不用开了。


1.制作步骤


列出动画的制作重点:

  1. 画风扇叶
  2. 绘出扇叶在不同旋转角度的图片
  3. 把以上的图片连贯起来,逐张播放


(图一)这就是我们将会制作的风扇效果图。


2.代码分析

function makecoolfan()% Demonstrates an animated fan-like plot and outputs as a GIF file.% Reference: "MATLAB 实用教程" / MATHWORKS.COM% Author: blog.csdn.com/freedigits% Date: May 26, 2013.% Parameter settingsradius = 1;         % radius of fannleaf = 3;          % number of leaves of fanleafstep = 0.01;    % shaping step of fan leafnframe = 10;        % number of frames in one complete rotationgiffile = 'mycoolfan.gif';       % output GIF file nameplotopts = 'g-';    % plot options% Intermediate paramstheta = (0 : leafstep : 2) * pi;        % theta array for one rotationdeltatheta = 2 * pi / nframe;           % delta angle between two consecutive frames% Construct the plots and store to matrixfigure(1);for n = 1 : nframe    offset = (n - 1) * deltatheta;      % calc new offset    r = radius * cos(nleaf * theta + offset);       % renew r    polar(theta, r, plotopts);          % present in polar plot    M(n) = getframe;                    % store plot result as a frameend% Write to GIFfor n = 1 : nframe    im = frame2im(M(n));                % convert frame to rgb image    [imind, cm] = rgb2ind(im, 8);       % get rgb image into palette representation of 8 colors    if 1 == n        imwrite(imind, cm, giffile, 'gif', 'Loopcount', inf, 'DelayTime', 0); % write w/GIF params for first frame    else        imwrite(imind, cm, giffile, 'gif', 'WriteMode', 'append');  % append other frames    endend% Play moviemovie(M, 10);       % play 10 times (i.e. 10 rotations)end

因为这台风扇的结构是旋转对称的,所以我们在极坐标(polar coordinates, 一个数据点p可以表示为(r,theta)))上画图会比较便捷。在极坐标上,三块旋转对称的扇叶,等价于直角坐标上一个周期性的波形(这点坐标转换可以说明)。如果我们认真看效果图,会发现每个扇叶占据了60度,而且扇叶之间有60度的间隔。由此,我们可以推断这个波形的周期是120度。cos(x)的周期是360度,cos(3x)的周期就是120度(3倍的变化速度)。另外,我们也能发现,r在扇叶间隔部分的值一直保持为0,这可以用r=cos(theta)表示么?答案是肯定的,因为在一般的极坐标上,r<0的数据点是不存在的,所以不予显示,也就说,我们可以把这些数据点的r值当作0。


另外,请留意上面的代码里这几个MATLAB函数:

  1. getframe: 把当前图形返回为一个帧的数据结构(struct)
  2. frame2im: 把帧的数据转为RGB图像矩阵
  3. rgb2ind: 将RGB图像矩阵转以调色板索引值表示
  4. imwrite: 将图像储存为文件

想得知这些函数的详细说明,请参考MATHWORKS.COM。


3.结论


要制作这个简单的风扇,其流程基本可归纳为3步:(1)规划(功能结构),(2)分析(实现原理),(3)行动(编写、调试)。
感想:这不纯粹是工程技巧,也是一种艺术。



原创粉丝点击