99 lines
3.3 KiB
Python
99 lines
3.3 KiB
Python
# ====================================================================
|
||
# 保存和输入matlat格式数据,并画图显示
|
||
#
|
||
# ====================================================================
|
||
import scipy.io as sio
|
||
import numpy as np
|
||
import matplotlib.pyplot as plt
|
||
from mpl_toolkits.mplot3d import Axes3D
|
||
import os
|
||
|
||
# 通过以下三段代码来保证scipy.io.savemat 函数的正常运行
|
||
|
||
# 指定要保存的文件路径
|
||
file_path = 'data/testpython.mat'
|
||
|
||
# 获取文件夹路径
|
||
folder_path = os.path.dirname(file_path)
|
||
|
||
# 如果文件夹不存在,则创建它
|
||
if not os.path.exists(folder_path):
|
||
os.makedirs(folder_path)
|
||
|
||
# 创建4个变量,并赋值
|
||
sio.savemat('data/testpython.mat', {'a': 1, 'b': 5, 'c': 3, 'd': 4})
|
||
"""
|
||
|
||
这行代码调用savemat函数来保存数据。
|
||
|
||
'data/testpython.mat':
|
||
这是你想要保存文件的路径和文件名。这里的例子中,文件会被保存在名为data的文件夹下,文件名为testpython.mat。
|
||
{'a': 1, 'b': 5, 'c': 3, 'd': 4}:
|
||
这是一个Python字典,其中包含了你想要保存到.mat文件中的数据。在这个例子中,你有四个键值对,键是'a', 'b', 'c', 和'd',相应的值是1, 5, 3, 和4。
|
||
|
||
注意:scipy.io.savemat 函数在保存 MATLAB 格式的 .mat 文件时,默认情况下不会自动创建不存在的文件路径。如果指定的文件路径不存在,函数会引发一个错误。
|
||
|
||
因此需要在使用scipy.io.savemat前确保文件存在
|
||
"""
|
||
|
||
|
||
# 创建了一个变量x,并赋予一个矩阵
|
||
sio.savemat('data/testpython2.mat', {'x': [[1, 3, 5, 4], [5, 3, 2, 8]]})
|
||
|
||
# 读取“testpython.mat”文件内容并赋值给data变量
|
||
data = sio.loadmat('data/testpython.mat')
|
||
# 同上
|
||
data2 = sio.loadmat('data/testpython2.mat')
|
||
|
||
|
||
# 创建一个内值全为零的数组变量x
|
||
x = np.zeros([1, 4])
|
||
"""
|
||
np.zeros()是NumPy提供的一个函数,用于创建一个包含零值的数组。
|
||
[1, 4]是传递给np.zeros()函数的参数,它指定了要创建的数组的形状。在这个例子中,它是一个包含1行和4列的数组。
|
||
"""
|
||
|
||
# 分别对x变量数组内的各值进行赋值
|
||
x[0][0] = data['a']
|
||
x[0][1] = data['b']
|
||
x[0][2] = data['c']
|
||
x[0][3] = data['d']
|
||
|
||
y = data2['x']
|
||
|
||
# 打印x及其数据类型,以及y矩阵中第一行的内容及其数据类型
|
||
print(x, f"x的数据类型为{x.dtype}", y[0], f"y中第一列的数据类型为{y[0].dtype}")
|
||
|
||
# 初始化一个图形对象,然后可以在该图形上绘制不同的图表或子图。
|
||
fig = plt.figure()
|
||
|
||
# 在fig上创建一个带有三维坐标系的子图
|
||
ax = fig.add_subplot(111, projection='3d')
|
||
"""
|
||
.add_subplot(111, projection='3d'):这是在图形对象 fig 中添加一个三维坐标系的子图的操作。
|
||
|
||
111:这个参数表示将图形分割成一个 1x1 的网格,并选择网格中的第一个位置。这意味着整个图形窗口只包含一个子图,占据整个窗口。
|
||
|
||
projection='3d':这个参数指定了子图的投影类型为三维坐标系(3D)。这意味着你可以在这个子图中绘制三维图表,例如三维散点图、曲面图等。
|
||
|
||
"""
|
||
|
||
# 设定散点的xyz数据
|
||
xs = x
|
||
ys = y[0]
|
||
zs = y[1]
|
||
|
||
# 画出对应位置的点
|
||
ax.scatter(xs, ys, zs, c='b', marker='o')
|
||
|
||
# 给xyz轴加上标签
|
||
ax.set_xlabel('x')
|
||
ax.set_ylabel('y')
|
||
ax.set_zlabel('z')
|
||
|
||
# 显示图像
|
||
plt.show()
|
||
|
||
# 释放资源并清除图形
|
||
plt.close()
|