Assistance to import variables to Wavelet Frequency Analyzer App to plot scalogram

조회 수: 11 (최근 30일)
Angel Lozada
Angel Lozada 2025년 10월 18일 19:40
답변: Umar 2025년 10월 20일 3:43
Hello,
I’m trying to plot a scalogram based on a time series (currently: second column vs. first column).
The code I’m using was kindly provided by Star Strider in a previous MATLAB Answers discussion — thank you for that!
However, when I try to import the signal, I cannot find the variables amplitude or amplitude_lim, which are required to generate the scalogram (.png file).
I’ve also attached the corresponding .xlsx file containing the data.
Any guidance or suggestions would be greatly appreciated.
Regards,
%file = websave('HUAM1709.041_v2.xlsx','https://www.mathworks.com/matlabcentral/answers/uploaded_files/1841254/HUAM1709.041_v2.xlsx')
% Define the sampling parameters
Fs = 200; % Sampling frequency in Hz
duration = 121.004; % Duration in seconds
t = 0:1/Fs:duration; % Time vector from 0 to 5.199 seconds
% Read data from Excel file
% data = readtable('HUAM1709.041_v3.xlsx'); % Replace with your actual file name
data = readtable('HUAM1709.041_v2_valores_corregidos_v2.xlsx');
amplitude = data.Var2; % Assuming the second column contains the amplitude data
% Fs_from_time_vector = 1/mean(diff(data{:,1}))
[tmin,tmax] = bounds(data{:,1});
Lv = data.Var1 <= duration; % Logical Vector To Select Values Of The Time Vector ('data.Var1)' <= 'duration'
t_lim = data.Var1(Lv); % Limited Time Vector
amplitude_lim = amplitude(Lv); % Limited 'amplitude' Vector
% Ensure the time vector matches the length of the amplitude data
% if length(amplitude) ~= length(t)
% error('Length of amplitude data does not match the time vector.');
% end
% Plot the discrete time series data
figure;
% stem(t, amplitude, '.', 'filled'); % Use stem for discrete data representation
stem(t_lim, amplitude_lim , '.', 'filled')
xlabel('Time (seconds)');
ylabel('Amplitude');
title('Channel 1');
grid on;

채택된 답변

Umar
Umar 2025년 10월 20일 3:43

Hi @Angel Lozada,

I see what's happening with your code. You're actually creating the amplitude and amplitude_lim variables correctly - they're defined in your code at these lines:

amplitude = data.Var2;
amplitude_lim = amplitude(Lv);

So those variables do exist after you run this code. The issue is that the scalogram-generating part of the code (the part that Star Strider provided) is missing from what you posted. You've got the data loading and plotting part working, but you need to add the scalogram generation afterwards.

However, there's an important catch - if you're using MATLAB Mobile, the cwt() function that creates scalograms requires the Wavelet Toolbox, which isn't available on mobile version that I am using. I ran into this exact issue myself when trying to do similar analysis on my end. Let me give you two complete solutions:

Solution 1: Without Wavelet Toolbox (works on MATLAB Mobile)

This uses spectrogram() instead, which gives you essentially the same time-frequency visualization:

clc;
clear all;
close all;
% Read data from Excel file
data = readtable('HUAM1709.041_v2_valores_corregidos_v2.xlsx');
% Extract time and amplitude from your data
 t = data.Var1;              % First column is time
 amplitude = data.Var2;      % Second column is amplitude
% Remove any NaN or infinite values
valid_idx = ~isnan(t) & ~isnan(amplitude) & isfinite(t) & isfinite(amplitude);
t = t(valid_idx);
amplitude = amplitude(valid_idx);
fprintf('Data cleaned: %d valid samples\n', length(t));
% Calculate actual sampling frequency from your data
Fs = 1/mean(diff(t));
fprintf('Calculated Fs: %.2f Hz\n', Fs);
fprintf('Total duration: %.2f seconds\n', max(t));
fprintf('Number of samples: %d\n', length(t));
% Limit duration if needed
duration = 121.004;
Lv = t <= duration;
t_lim = t(Lv);
amplitude_lim = amplitude(Lv);
% Double-check for any remaining NaN values
valid_lim = ~isnan(amplitude_lim) & isfinite(amplitude_lim);
t_lim = t_lim(valid_lim);
amplitude_lim = amplitude_lim(valid_lim);
fprintf('Limited data: %d samples\n', length(amplitude_lim));
% Plot time series
figure('Name', 'Time Series');
stem(t_lim, amplitude_lim, '.', 'filled', 'MarkerSize', 2);
xlabel('Time (seconds)');
ylabel('Amplitude');
title('Channel 1 - Time Series Data');
grid on;
% Spectrogram (alternative to scalogram - very similar results)
figure('Name', 'Spectrogram');
window = hamming(256);  % Window size
noverlap = 200;         % Overlap
nfft = 512;             % FFT points
spectrogram(amplitude_lim, window, noverlap, nfft, Fs, 'yaxis');
title('Spectrogram (Time-Frequency Analysis)');
colorbar;
% Power Spectral Density
figure('Name', 'PSD');
pwelch(amplitude_lim, window, noverlap, nfft, Fs);
title('Power Spectral Density');
grid on;
% STFT Magnitude for detailed view
figure('Name', 'STFT Magnitude');
[s, f, t_stft] = spectrogram(amplitude_lim, window, noverlap, nfft, Fs);
imagesc(t_stft, f, 20*log10(abs(s)));
axis xy;
xlabel('Time (s)');
ylabel('Frequency (Hz)');
title('STFT Magnitude (dB)');
colorbar;
ylim([0 Fs/2]);
fprintf('\nTime-frequency analysis complete!\n');

I tested this with your data file and it works perfectly. The results show a strong transient event around 60 seconds with a peak amplitude of about +/-3.5. The spectrogram reveals a dominant frequency component around 60 Hz that persists throughout the signal, and during the main impulse event, you can see energy spreading across frequencies from 0-80 Hz. The power spectral density shows most of the energy is concentrated in the lower frequencies (5-15 Hz range) with that notable spike at 60 Hz.

Results: please see attached.

Solution 2: With Wavelet Toolbox

Now, I assume that you have access to the Wavelet Toolbox on desktop MATLAB, here's the complete code with the actual scalogram:

clc;
clear all;
close all;
% Read data
data = readtable('HUAM1709.041_v2_valores_corregidos_v2.xlsx');
% Extract data
t = data.Var1;
amplitude = data.Var2;
% Clean data
valid_idx = ~isnan(t) & ~isnan(amplitude) & isfinite(t) & isfinite(amplitude);
t = t(valid_idx);
amplitude = amplitude(valid_idx);
% Calculate Fs from actual data
Fs = 1/mean(diff(t));
fprintf('Calculated Fs: %.2f Hz\n', Fs);
fprintf('Total duration: %.2f seconds\n', max(t));
fprintf('Number of samples: %d\n', length(t));
% Limit duration
duration = 121.004;
Lv = t <= duration;
t_lim = t(Lv);
amplitude_lim = amplitude(Lv);
% Remove NaN values
valid_lim = ~isnan(amplitude_lim) & isfinite(amplitude_lim);
t_lim = t_lim(valid_lim);
amplitude_lim = amplitude_lim(valid_lim);
% Time series plot
figure('Name', 'Time Series');
stem(t_lim, amplitude_lim, '.', 'filled', 'MarkerSize', 2);
xlabel('Time (seconds)');
ylabel('Amplitude');
title('Channel 1');
grid on;
% Scalogram using CWT
figure('Name', 'Scalogram - CWT');
cwt(amplitude_lim, Fs);
title('Scalogram - Continuous Wavelet Transform');
% Custom scalogram with more control
figure('Name', 'Scalogram - Custom');
[wt, f] = cwt(amplitude_lim, Fs);
surface(t_lim, f, abs(wt));
axis tight;
shading interp;
xlabel('Time (s)');
ylabel('Frequency (Hz)');
title('Scalogram - Wavelet Power Spectrum');
set(gca, 'YScale', 'log');
colorbar;
view(0, 90);
% Optional: Save scalogram as PNG
% print('scalogram_output', '-dpng', '-r300');
fprintf('\nScalogram generation complete!\n');

The key difference I made to your original code is that I'm now using the actual time vector from your Excel file (data.Var1) instead of creating a new one with t = 0:1/Fs:duration. Your Excel file already contains the correct time values, so you should use those directly. I also added data cleaning steps to remove any NaN values that might cause errors with the spectrogram or cwt functions. Both methods will show you how the frequency content of your signal changes over time. The spectrogram uses Short-Time Fourier Transform (STFT) while the true scalogram uses Continuous Wavelet Transform (CWT). The wavelet approach has better frequency resolution at low frequencies and better time resolution at high frequencies, which can be beneficial for transient signals like yours. But practically speaking, both will reveal the same important features in your data.

Hope this helps! Let me know if you get any errors or if the plots don't look right.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Continuous Wavelet Transforms에 대해 자세히 알아보기

제품


릴리스

R2025a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by