Loading multiple spectra .mat files into python

44 Views Asked by At

I am trying to load multiple .mat files into python, the variable names are correct (double checked) and I would like to plot the spectra. I keep getting this error

KeyError: 'fib4_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()
1

There are 1 best solutions below

3
Ferro Luca On

KeyError most of the times means that the key does not exist.

Check all the keys you have with: mat_data.key()