read
Read next consecutive signal observation
Description
Examples
Read File Data in Signal Datastore
Specify the path to a set of audio signals included as MAT-files with MATLAB®.
folder = fullfile(matlabroot,'toolbox','matlab','audiovideo');
Create a signal datastore that points to the specified folder and set sample rate variable name toFs
. List the names of the MAT-files in the datastore.
年代ds = signalDatastore(folder,'FileExtension','.mat','SampleRateVariableName','Fs'); [~,c] = fileparts(sds.Files)
c =7x1 cell{'chirp' } {'gong' } {'handel' } {'laughter'} {'mtlb' } {'splat' } {'train' }
While the signal datastore has unread files, read consecutive files from the datastore. Use theprogress
function to monitor the fraction of files read.
whilehasdata(sds) [data,info] = read(sds); fprintf('Fraction of files read: %.2f\n',progress(sds))end
Fraction of files read: 0.14 Fraction of files read: 0.29 Fraction of files read: 0.43 Fraction of files read: 0.57 Fraction of files read: 0.71 Fraction of files read: 0.86 Fraction of files read: 1.00
Print and inspect theinfo
年代tructure returned by the last call to theread
function.
info
info =年代truct with fields:SampleRate: 8192 TimeVariableName: "Fs" SignalVariableNames: "y" FileName: "/mathworks/devel/bat/Bdoc21b/build/matlab/toolbox/matlab/audiovideo/train.mat"
Signal Datastore with In-Memory Data
Create a signal datastore to iterate through the elements of an in-memory cell array of signal data. The data consists of a sinusoidally modulated linear chirp, a concave quadratic chirp, and a voltage controlled oscillator. The signals are sampled at 3000 Hz.
fs = 3000; t = 0:1/fs:3-1/fs; data = {chirp(t,300,t(end),800).*exp(2j*pi*10*cos(2*pi*2*t));...2*chirp(t,200,t(end),1000,'quadratic',[],'concave');...vco(sin(2*pi*t),[0.1 0.4]*fs,fs)}; sds = signalDatastore(data,'SampleRate',fs);
While the datastore has data, read each observation from the signal datastore and plot the short-time Fourier transform.
plotID = 1;whilehasdata(sds) [dataOut,info] = read(sds); subplot(3,1,plotID) stft(dataOut,info.SampleRate) plotID = plotID + 1;end
Compute Envelopes of Signals
Specify the path to four signals included with MATLAB®. The signals are recordings of a bird chirp, a gong, a train, and a splat. All signals are sampled at 8192 Hz.
folder = fullfile(matlabroot,'toolbox','matlab','audiovideo',...["chirp.mat","gong.mat","train.mat","splat.mat"]);
Create a signal datastore that points to the specified files. Each file contains the variableFs
that denotes the sample rate.
年代ds1 = signalDatastore(folder,'SampleRateVariableName','Fs');
Define a function that takes the output of theread
function and calculates the upper and lower envelopes of the signals using spline interpolation over local maxima separated by at least 80 samples. The function also returns the sample times for each signal.
function[dataOut,infoOut] = signalEnvelope(dataIn,info) [dataOut(:,1),dataOut(:,2)] = envelope(dataIn,80,'peak'); infoOut = info; infoOut.TimeInstants = (0:length(dataOut)-1)/info.SampleRate;end
Call thetransform
function to create a second datastore,年代ds2
, that computes the envelopes of the signals using the function you defined.
年代ds2 = transform(sds1,@signalEnvelope,"IncludeInfo",true);
Combine年代ds1
and年代ds2
create a third datastore. Each call to theread
function from the combined datastore returns a matrix with three columns:
The first column corresponds to the original signal.
The second and third columns correspond to the upper and lower envelopes, respectively.
年代dsCombined = combine(sds1,sds2);
Read and display the original data and the upper and lower envelopes from the combined datastore. Use theextractBetween
function to extract the file name from the file path.
tiledlayout('flow')whilehasdata(sdsCombined) [dataOut,infoOut] = read(sdsCombined); ts = infoOut{2}.TimeInstants; nexttile holdonplot(ts,dataOut(:,1),'Color','#DCDCDC','LineStyle',':') plot(ts,dataOut(:,2:3),'Linewidth',1.5) holdoffxlabel('Time (s)') ylabel('Signal') title(extractBetween(infoOut{:,2}.FileName,'audiovideo\','.mat'))end
Find Spectrogram of Chirps
Specify the path to four files included with Signal Processing Toolbox™. Each file contains a chirp and a random sample rate,fs
, ranging from 100 to 150 Hz. Create a signal datastore that points to the specified folder.
folder = fullfile(matlabroot,'examples','signal','data','sample_chirps',...["chirp_1.mat","chirp_4.mat","chirp_9.mat","chirp_10.mat"]); sds = signalDatastore(folder,'SampleRateVariableName','fs');
Define a function that takes the output of theread
function and computes and returns:
The spectrograms of the chirps.
The vector of time instants corresponding to the centers of the windowed segments.
The frequencies corresponding to the estimates.
function[dataOut,infoOut] = extractSpectrogram(dataIn,info) [dataOut,F,T] = pspectrum(dataIn,info.SampleRate,'spectrogram',...'TimeResolution',0.25,...'OverlapPercent',40,'Leakage',0.8); infoOut = info; infoOut.CenterFrequencies = F; infoOut.TimeInstants = T;end
Call thetransform
function to create a datastore that computes the spectrogram of each chirp using the function you defined.
年代dsNew = transform(sds,@extractSpectrogram,'IncludeInfo',true);
While the transformed datastore has unread files, read from the new datastore and visualize the spectrograms in three-dimensional space.
t = tiledlayout('flow');whilehasdata(sdsNew) nexttile [sig,infoOut] = read(sdsNew); waterfall(infoOut.TimeInstants,infoOut.CenterFrequencies,sig) xlabel('Frequency (Hz)') ylabel('Time (S)') view([30 70])end
Partition Signal Datastore into Default Number of Parts
Specify the file path to the example signals included with MATLAB®. Create a signal datastore that points to the specified folder.
folder = fullfile(matlabroot,'toolbox','matlab','audiovideo'); sds = signalDatastore(folder,'SampleRateVariableName','Fs');
Get the default number of partitions for the signal datastore.
n = numpartitions(sds)
n = 7
Partition the datastore into the default number of partitions and return the datastore corresponding to the fourth partition.
年代ubsds = partition(sds,n,4);
Use theextractAfter
function to display the name of the file contained in the datastore corresponding to the fourth partition.
fName = extractAfter(subsds.Files,'audiovideo\')
fName =1x1 cell array{0x0 char}
Read the data and information about the signal in the datastore corresponding to the fourth partition. Extract the sample rate frominfo
and resample the signal to half the original sample rate. Plot the original and resampled signals.
whilehasdata(subsds) [data,info] = read(subsds); fs = info.SampleRate; f_res = 0.5*fs; ts = (0:length(data)-1)/fs; data_res = resample(data,1,2); t_res = (0:length(data_res)-1)/f_res; plot(ts,data,t_res,data_res,':') xlabel('Time (s)') ylabel('Signal') legend('Original','Resampled','Location','NorthWest')end
Input Arguments
年代ds
—Signal datastore
年代ignalDatastore
object
Signal datastore, specified as a年代ignalDatastore
object.
Output Arguments
年代ig
— Signal data
array
Signal data, returned as an array. By default, callingread
once returns the first variable of one file at a time. If you set theReadSizeproperty ton, such thatn> 1, each time you call theread
function, the function reads:
The first variable of the firstnfiles, if
年代ds
contains file data.The firstnmembers, if
年代ds
contains in-memory data.
Note
To determine the name of the first variable in a file,read
follows these steps:
For MAT-files:
年代= load(fileName); varNames = fieldnames(s); firstVar = s.(varNames{1});
For CSV files:
opts = detectImportOptions(fileName,'PreserveVariableNames',true); varNames = opts.VariableNames; firstVar = string(varNames{1});
If theSignalVariableNames
property of the datastore contains more than one signal name, then年代ig
is a cell array. Use theReadOutputOrientation
property of the datastore to control the orientation of年代ig
as either a column array or a row array.
info
— Information about signal data
年代tructure
Information about signal data, returned as a structure.
In case of file data,
info
contains the time information (if specified), file names, and the variable names used to read signal and time data, if this information was specified in the年代ignalDatastore
.If the datastore contains in-memory data,
info
contains time information (if specified) and member names.
Open Example
You have a modified version of this example. Do you want to open this example with your edits?
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select:.
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina(Español)
- Canada(English)
- United States(English)
Europe
- Belgium(English)
- Denmark(English)
- Deutschland(Deutsch)
- España(Español)
- Finland(English)
- France(Français)
- Ireland(English)
- Italia(Italiano)
- Luxembourg(English)
- Netherlands(English)
- Norway(English)
- Österreich(Deutsch)
- Portugal(English)
- Sweden(English)
- Switzerland
- United Kingdom(English)