matlab 语法_"囧"字图: MATLAB与Python的语法对比

d7020dc3d93e86106e238eb64f06225b.png
知乎视频​www.zhihu.com
zhihu-card-default.svg

这个程序来源于

http://www.matlabsky.com/thread-11364-1-1.html

经过我的改进,效果更佳.如下图所示:

2aee8f5e318813f5fe17664194730796.png

MATLAB代码如下:

clear;clc;close all;
% 画出"囧"字的两个眉毛和一张嘴
x = -3 : 0.1 : 3;
y = 1 ./ (x .^ 2 - 1);
plot(x, y, 'r', 'LineWidth', 3.5);
hold on;
% 画出"囧"字的方框
plot([-3,  3], [-3, -3], 'r', 'LineWidth', 3.5);
plot([-3,  3], [ 3,  3], 'r', 'LineWidth', 3.5);
plot([-3, -3], [-3,  3], 'r', 'LineWidth', 3.5);
plot([ 3,  3], [-3,  3], 'r', 'LineWidth', 3.5);
% 设定曲线的范围
axis([-3, 3, -3, 3]);
% 让"囧"字四四方方
axis equal;
% 去掉坐标轴
axis off;
% 生成"囧.png"文件
print('囧', '-dpng');

Python代码如下:

# -*- coding: utf-8 -*-
"""
Created on Mon May 11 19:35:13 2020

@author: lihaitao
"""

#%% load
import matplotlib.pyplot as plt
import numpy as np
from numpy import ma
plt.close("all")

#%%
# 画出"囧"字的两个眉毛和一张嘴
x = np.arange(-3.0, 3.0 + 1e-6, 0.1)
x = ma.masked_where(np.abs(x ** 2 - 1) < 1e-6, x)
y = 1 / (x ** 2 - 1)

plt.figure()
plt.plot(x, y, 'r', LineWidth=3.5)

# 画出"囧"字的方框
plt.plot([-3,  3], [-3, -3], 'r', LineWidth=3.5)
plt.plot([-3,  3], [ 3,  3], 'r', LineWidth=3.5)
plt.plot([-3, -3], [-3,  3], 'r', LineWidth=3.5)
plt.plot([ 3,  3], [-3,  3], 'r', LineWidth=3.5)

# 让"囧"字四四方方
plt.axis('equal')

# 设定曲线的范围
plt.axis([-3, 3, -3, 3])

# 去掉坐标轴
plt.axis('off')
# 生成"囧.png"文件
plt.savefig('囧.png')

f0c414ab81e124e0552b31b87dd40615.png

可以发现:

1 Python的语法(matplotlib库)与MATLAB的语法非常相似

这个绝对不是巧合!

matplotlib有两套语法体系, 一套是OOP语法, 另一套就是命令式的, 而命令式的语法是模仿MATLAB的语法, 目的(我猜测)是为了抢夺MATLAB的用户.

2 "plt.axis([-3, 3, -3, 3])"必须写在"plt.axis('equal')"下面, 而MATLAB的话, 顺序无所谓.

读者可以试一下改变这两个命令的顺序, 看看效果有什么区别.

3 必须借助掩码(mask), 来实现非连续的曲线, 而MATLAB自动实现.

如果删除"x = ma.masked_where(np.abs(x ** 2 - 1) < 1e-6, x)", 看看效果有什么变化:

9511b1bf42efcadc64080b1d1a96dc42.png

多了两条"法令纹".

创作不易, 请大家"素质三连": 点赞, 收藏, 分享.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值