aan
aan

Reputation: 121

How can I automatically let Matlab input the file in sequence?

How can I let Matlab automatically input the file itself rather than one by one myself?

I mean, I want to put Sample 1.wav and then output Sample 1.png and then put Sample 2.wav and then output Sample 2.png and then put Sample 3.wav and then output Sample 3.png

I do not want to type myself 1, 2, 3 and rather let the matlab run itself from 1 to 1,000

[y,Fs] = audioread('sample1.wav');
spectrogram(y,'yaxis')
saveas(gcf,'sample1.png')

Then

[y,Fs] = audioread('sample2.wav');
spectrogram(y,'yaxis')
saveas(gcf,'sample2.png')

Then

[y,Fs] = audioread('sample3.wav');
spectrogram(y,'yaxis')
saveas(gcf,'sample3.png')

Upvotes: 1

Views: 86

Answers (1)

mimocha
mimocha

Reputation: 1121

To programmatically iterate through files, use the dir command to get a list of all files in a directory. Documentation for dir

For example, you can get a list of files in the current directory with the command:

list = dir
list = 

  4×1 struct array with fields:

    name
    folder
    date
    bytes
    isdir
    datenum

In this case, I have 2 files in the current directory, with the addition of 2 inodes ('.' and '..'). These are all stored in a struct array called list. You can see the list of files by the command:

{list.name}
ans =

  1×4 cell array

    {'.'}    {'..'}    {'fileA.m'}    {'fileB.m'}

Filenames can be generated programmatically with sprintf(). Documentation for sprintf

for i = 1:10
    sprintf("sample%d.png", i)
end
ans = 

    "sample1.png"
ans = 

    "sample2.png"
ans = 

    "sample3.png"
...

Combine the two together, and you can iterate through all of the files in the list with a code like so:

list = dir; % Get files in current directory
fileList = {list.name}; % Store filenames in a cell array
fileList(1:2) = []; % Delete the inodes '.' and '..'

for i = 1:length(fileList)
    % Get current filename, use curly brackets to extract string from cell array
    currentFile = fileList{i}; 
    
    % Use sprintf() to automatically generate filenames
    saveName = sprintf("sample%d.png", i); 

    % Your code goes here
    [y,Fs] = audioread(currentFile);
    spectrogram(y,'yaxis')
    saveas(gcf,saveName)
end

If moving to the directory of the target files is inconvenient, you can give the dir command a target directory: list = dir('C:/TargetDirectory/'). This will give you the list of files in that directory, but note that you will have to add that target directory to the MATLAB path, or explicitly add that to the target filename when loading. E.g.:

% Directory path, use double quotes, not single quotes
targetDirectory = "C:/TargetDirectory/";

currentFile = fileList{i};
currentFile = targetDirectory + currentFile; % Append path to file

% Do stuff
load(currentFile)

Upvotes: 4

Related Questions