matlab 将多个spectro.mat文件加载到python中

shyt4zoc  于 7个月前  发布在  Matlab
关注(0)|答案(1)|浏览(80)

我正试图将多个.mat文件加载到python中,变量名称是正确的(双重检查),我想绘制光谱。我一直收到这个错误
KeyError:'site4_spec'

import os
import matplotlib.pyplot as plt
from scipy.io import loadmat
%matplotlib inline
%matplotlib widget

# Directory containing the .mat files
mat_files_dir = '/Users/xxxxx/Desktop/Tau Ceti/'

# List all .mat files in the directory
mat_files = [file for file in os.listdir(mat_files_dir) if file.endswith('.mat')]

# Iterate through each .mat file
for mat_file in mat_files:
    mat_data = loadmat(os.path.join(mat_files_dir, mat_file))

    # Access the relevant variables 
    spectrum_amplitude = mat_data['fib4_spec']  
    spectrum_wave = mat_data['fib4_spec_wave'] 

    # Get the number of absorption lines (rows)
    num_lines = spectrum_amplitude.shape[0]

    # Create a single plot with subplots
    plt.figure(figsize=(12, 6))  

    for line_index in range(num_lines):
        line_amplitude = spectrum_amplitude[line_index]
        line_frequency = spectrum_wave[line_index]
        plt.plot(line_frequency, line_amplitude, label=f'Line {line_index+1}')

    plt.xlabel('Frequency')
    plt.ylabel('Amplitude')
    plt.title('Tau Ceti - ' + os.path.splitext(mat_file)[0])
    plt.legend()
    plt.show()
t8e9dugd

t8e9dugd1#

KeyError大多数情况下意味着密钥不存在。
检查您拥有的所有钥匙:mat_data.key()

相关问题