matlab绘图的三种方法:已知函数表达式

matlab经常要使用函数进行绘图,举个栗子,要绘制下面的函数应该怎么绘制呢?

f ( x ) = s i n ( x ) ∗ ( 1 − x 2 ) f(x)=sin(x)*(1-x^2) f(x)=sin(x)(1x2)

总结有以下三种方法:

1.for循环

这是最最原始的方法了,不推荐

clear 
t=linspace(0,20,501);
fi=zeros(1,501);
for ii=1:length(t)
	f1(ii)=sin(t(ii))*(1-t(ii)^2);
end
plot(t,f1,'-')

2.直接计算

matlab有强大的矩阵运算能力,使得问题非常的方便~但是需要把运算符号加上点号 ⋅ \cdot ∗ * 改成.*,把^ 改成.^。

clear 
t=linspace(0,20,501);
f1=sin(t).*(1-t.^2);
plot(t,f1,'-')

3.使用subs函数

另外还可以使用subs函数,可以提前规定一个函数,利用subs函数进行赋值。

tic
clear 
syms x
f=sin(x)*(1-x^2);
t=linspace(0,20,501);
f1=subs(f,x,t); 
plot(t,f1,'-')
toc

对比

对三种方法进行了运行时间的测试:
方法2最优(直接计算),方法1次之,方法3最慢。

在这里插入图片描述
附上测试的代码

clear
t=linspace(0,20,501);
% 第一种方法
tic;
fi=zeros(1,501);
for ii=1:length(t)
	f1(ii)=sin(t(ii))*(1-t(ii)^2);
end
t1=toc;
% 第二种方法
tic;
f2=sin(t).*(1-t.^2);
t2=toc;
% 第三种方法
tic;
syms x
f=sin(x)*(1-x^2);
f3=subs(f,x,t); 
t3=toc;
%plot(t,f1,'-')
subplot(1,3,1)
plot(t,f1)
title(['方法1用时',num2str(t1),'s'])
subplot(1,3,2)
plot(t,f2)
title(['方法2用时',num2str(t2),'s'])
subplot(1,3,3)
plot(t,f3)
title(['方法3用时',num2str(t3),'s'])
  • 8
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值