【Matlab】关于Matlab的一些代码片段

转载,请保持连接:http://blog.csdn.net/stalendp/article/details/44904639

这篇文章收集关于Matlab的一些代码片段,以便查阅:

1. 方波

 

function [] = myFunc(n)
    t = 0:0.001:2;
    y = myFunc0(t, n);
    figure;
    plot(t, y);
end

% 方波
function [ y ] = myFunc0( t, n )
rt = 0;
for k = 0:n
    rt = rt + sin(2*pi*(2*k+1)*t)/(2*k+1);
end
y = rt * 4 / pi;
end

方波图如下:

2. 打印3D曲面

 

 [x,y] = meshgrid(-8:.1:8);
 z = (2.*x.*y)./(x.*x + y.*y);
mesh(x,y,z);

 

3. 一些打印技巧

 

 

% example 1
x = linspace(0,pi);
y = sin(x);
ymax = max(y);
figure(1)
plot(x, y, '-b')
hold on
plot(xlim, [1 1]*ymax, '-r')
hold off
axis([xlim    0  1.1])

% example 2
x = linspace(0,5,1000);
y = sin(100*x)./exp(x);
ax1 = subplot(2,1,1);
plot(x,y)

ax2 = subplot(2,1,2);
plot(x,y)
xlim(ax2,[0 1])

 

 

4. 函数的一些使用技巧(function handler, anonymous function); 

 

可以使用matlab中的类来 更好的管理函数模块,请参考5中的方法

 

function study(n)
    sqr = @(nn) nn.^2;
    C = {@e1, @e2, @e3, @e4, @() sqr(3)};
    C{n}()
end

%相关快捷键:Ctrl+R, Ctrl+T, Ctrl+I %{ %}
function e1
    disp('This is example1');
    figure(1)
    x = linspace(0,pi);
    y = sin(x);
    ymax = max(y);
    plot(x, y, '-b')
    hold on
    plot(xlim, [1 1]*ymax, '-r')
    hold off
    axis([xlim    0  1.1])
end

function e2
    disp('This is example2');
    figure(2)
    x = linspace(0,5,1000);
    y = sin(100*x)./exp(x);
    ax1 = subplot(2,1,1);
    plot(x,y)

    ax2 = subplot(2,1,2);
    plot(x,y)
    xlim(ax2,[0 1])
end

function e3
    disp('This is example3');
    figure(3)
    [x,y] = meshgrid(-8:.1:8);  
    z = (2.*x.*y)./(x.*x + y.*y);  
    mesh(x,y,z);      
end

function e4
    disp('This is example4');
    figure(4)
    myFunc(20);
end

5. 用类的方式来管理函数模块

 

classdef myclass
    properties
    end
    
    methods
        function e1(obj)
            disp('This is example1');
            figure(1)
            x = linspace(0,pi);
            y = sin(x);
            ymax = max(y);
            plot(x, y, '-b')
            hold on
            plot(xlim, [1 1]*ymax, '-r')
            hold off
            axis([xlim    0  1.1])
        end
        
        function e2(obj)
            disp('This is example2');
            figure(2)
            x = linspace(0,5,1000);
            y = sin(100*x)./exp(x);
            ax1 = subplot(2,1,1);
            plot(x,y)
            
 
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值