How to do batch export (into txt file) in eeglab? - matlab

I got a batch of processed datasets in eeglab. I want to export all of them into txt in a batch, however, it seems like must be done file by file.
I am new to eeglab and matlab. Could someone please help me with this?

This code was tested by being run in my directory with EEGLAB in it. In my case there are 2 data sets with associated .fdt files in that directory as well. If your .set files are in a different directory from EEGLAB, you will have to change the code to find them there. The script must be in the EEGLAB directory, or else the EEGLAB source must be in your PATH, but I think that putting EEGLAB's code in your PATH is not a recommended setup.
I use regular expression (regexp) to find which files are .set files and to build the output filenames. If you are not familiar with regular expressions, just do a websearch.
% read all the files in the directory
files = dir();
% parse directory contents for .set files
sets = {};
idx = 1;
for n=1:length(files)
if(regexp(files(n).name,'.set'))
sets{idx} = files(n).name;
idx = idx+1;
end
end
% load the data sets and write the data to appropriate filename
for n=1:length(sets)
% change the argument after filepath to the path your EEGLAB
% instalation is in
% note the double '\' directory delimiter is for Windows
EEG = pop_loadset('filename', sets{n},'filepath','C:\\Users\\david.medine\\matlab\\toolboxes\\eeglab2019_0\\');
EEG = eeg_checkset( EEG );
outputfilename = sprintf('%stxt', sets{n}(1:regexp(sets{n}, '.set')))
writematrix(EEG.data, outputfilename);
end
By the way, I knew what functions to call from EEGLAB to load the .set files by checking >> EEG.history. That will show all the Matlab code that went on behind the GUI scenes in your EEGLAB session.
EEGLAB stores the data in vectorized orientation. If you want multiplexed simply transpose the matrix:
writematrix(EEG.data', outputfilename);

Related

How to load and run multiple .mat files in matlab

I am trying to run multiple .mat files in matlab. So far i have 3 .mat files each containing the same variables. I want to run one .mat file and then switch to the next file. They are named like this:
file2019_1.mat %day 1
file2019_2.mat %day 2
file2019_3.mat %day 3
The code i have tried to run works for the first .mat file and it then doesnt switch to the second. Ideally i am trying to run all 3 files continuously, as in the future i could have 100s.
This is the code i tried so far:
% set up folder for .mat files containing variables of interest
myFolder = ('filepath');
filePattern = fullfile(myFolder, 'file2019_*.mat');
fileList = dir(filePattern);
% set up variable data (here it is daily mean velocity value)
% hourly, m/s (one mat file one day)
number_mat = length(fileList);
for i = 1:number_mat
load(['file2019_' num2str(i) '.mat'])
%%%% run model in here
end
Any help on how i could get this to run continuously through each mat file would be great.
Thank you.
A very easy method , just select all the files (Ctrl + A) - drag and drop them into the command window (be sure to drag the first file to load them in same order).
Or You can use this
% Read files mat1.mat through mat20.mat
for k = 1 : 20 % or whatever your numbers of files
% Create a mat filename, and load it into a structure called matData.
matFileName = sprintf('mat%d.mat', k);
if isfile(matFileName)
matData = load(matFileName);
else
fprintf('File %s does not exist.\n', matFileName);
end
end
Or
% Get a list of all txt files in the current folder, or subfolders of it.
fds = fileDatastore('*.txt', 'ReadFcn', #importdata)
fullFileNames = fds.Files
numFiles = length(fullFileNames)
% Loop over all files reading them in and plotting them.
for k = 1 : numFiles
fprintf('Now reading file %s\n', fullFileNames{k});
% Now have code to read in the data using whatever function you want.
% Now put code to plot the data or process it however you want...
end

Writing to text file in matlab

I want to do some operations on images and write some data into a txt file.Here is what I am doing for one image-
clc;
image=imread('im.png');
.... %do some operations
....
....
fileID=fopen('first.txt','w');
.... %write onto the txt file
....
fclose(fileID);
But I want to do this for many images.I have stored all the images in a folder.Also, I want to continue writing in the same text file immediately after where I left off for the previous image.How can I modify my code to achieve this?
Well that's pretty simple. Use a loop and loop over all of your images, do your processing on it, then append to the text file. What'll be easier is that you just open the file for your text ONCE, write for as many times as you have images, then finally close it.
Something like this:
folder = ...; %// Place folder here - Example: folder = fullfile('D:', 'images');
fileID=fopen('first.txt','w'); %// Open up the file for writing
f = dir(fullfile(folder, '*.png')); %// look for all PNG files in this folder
for idx = 1 : numel(f)
filename = fullfile(folder, f(idx).name); %// Get the file name
im = imread(filename); %// Read the image in
.... %do some operations
....
....
.... %write onto the txt file
....
fprintf(fileID, '\n\n'); %// Put two carriage returns to make way for next file
end
fclose(fileID);
The function dir scans for all files that match a particular expression. In your case, you want to find all PNG files in a particular folder of your choosing. I assume that this is stored in the variable folder. We then open up the file first before we do anything to the images, then loop over each of the found images with dir. Take note that when you use dir, it only finds the relative paths to the files (i.e. just the names themselves). If you want to locate where the actual images are, you need the absolute paths, which is why we use fullfile.
So, for each PNG image that's in the folder, load it in, do your processing on it, write to your file and I make sure that I put in two carriage returns to separate each result. You repeat this for each PNG image until you exhaust all of them from the folder. Once you're done, you close the text file.
Minor note
image is an actual function in MATLAB that visualizes a matrix of values as an image with a specified colour map. You should probably rename this variable to something else so you don't overshadow the function in case other scripts / functions you write use this function.

save specific files with MATLAB commands

I'm trying to save models in oldest MATLAB versions as below
I look for each folder and subfolder to find any .mdl or .slx to save it as 2007b version
The problem I have is :
it works if I just look for one extension whereas I'm wondering
to do that on each .mdl and.slx .
the save_system takes too much
time
Do you know how could I get all .mdl and .slx and is there an optimized way to save ?
Thanks
rootPath = fullfile('M:\script\ytop','tables');
files = dir(rootPath );
for ii = 3:numel(files)
x = fullfile(rootPath ,files(ii).name);
cd(x);
mdl = { dir('*.mdl'),dir('*.slx')}; % here it works if only I set dir('*.mdl')
for jj = 1:numel(mdl)
load_system(mdl(jj).name);
save_system(mdl(jj).name,mdl(jj).name, 'SaveAsVersion','R2007b');
end
end
%here you used {} which created a cell array of two structs. cat creates a single struct which.
mdl=cat(1,dir('*.mdl'),dir('*.slx'));
for jj = 1:numel(mdl)
[~,sysname,~]=fileparts(mdl(jj).name);
load_system(mdl(jj).name);
%use only sysname without extension. R2007b is mdl only. You can't store files for R2007b in slx format
save_system(sysname,sysname, 'SaveAsVersion','R2007b');
%close system to free memory.
close_system(sysname);
end
Applying only the required fixes your code has one odd behaviour. For mdls the file is replaced with the original one, for slx a mdl is created next to the original one. You may want to add a delete(mdl(jj).name) after loading.

Saving image using MATLAB

I made a program in MATLAB to generate images with different specifications, but each time I change one of theses specifications I had to re-save the image under a different name and path. So, I made a for loop to change these specifications, but I don't know how I can make MATLAB save the generated image with different names and different paths...
How can I write a program to make MATLAB save multiple generated images with different names and different paths as a part of for–loop?
Put something like this at the end of your loop:
for i = 1:n
<your loop code>
file_name=sprintf('%d.jpg',i); % assuming you are saving image as a .jpg
imwrite(your_image, file_name); % or something like this, however you choose to save your image
end
If you want to save JPEG, PNG etc., then see #AGS's post. If you want to save FIG files, use
hgsave(gcf, file_name)
instead of the imwrite line. There's also
print('-djpeg', file_name) %# for JPEG file (lossy)
print('-dpng', file_name) %# for PNG file (lossless)
as an alternative for imwrite.
Since I wanted to save the plots in my loop in a specific folder in my present working directory (pwd), I modified my naming routine as follows:
for s = 1:10
for i = 1:10
<loop commands>
end
end
% prints stimuli to folder created for them
file_name=sprintf('%s/eb_imgs/%0.3f.tif',pwd,s(i)); % pwd = path of present working
% directory and s(i) = the value
% of the changing variable
% that I wanted to document
file_name = /Users/Miriam/Documents/PSYC/eb_imgs/0.700.tif % how my filename appears
print('-dtiff', '-r300', file_name); % this saves my file to my desired location
matlab matlab-path

how to read wav files one after other from the same folder in Matlab

I am trying to write a program where i have to read a wav file, extract some features from it and save them and then go and pick the next file repeat the same procedure. the number of wave files to be picked are more than 100. Can someone help me how to read wavfiles one after another. (say the files are named e1.wav,e2.wav and so on). someone please help me
The dir command is quite helpful here. It either displays the whole content of a directory but you can also specify a glob to just return a sub-set of files, e.g. dir('*.wav'). This returns an struct-array containing file information such as name, date, bytes, isdir and so on.
To get started, try the following:
filelist = dir('*.wav');
for file = filelist
fprintf('Processing %s\n', file.name);
fid = fopen(file.name);
% Do something here with your file.
fclose(fid);
end
Edit 1: Change the double-quotes to single-quotes (thx to user1540393).
Edit 2 (Suggested by amro): If a processing result has to be stored per file,
I often use the following pattern. I usually pre-allocate an array, a struct array or
a cell array of the same size as the filelist. Then I use an integer index to iterate
over the file list, which I can also use to write the output. If the information to be
stored is homogeneous (e.g. one scalar per file), use an array or a struct array.
However, if the information differs from file to file (e.g. vectors or matrices of different size) use a cell array instead.
An example using an ordinary array:
filelist = dir('*.wav');
% Pre-allocate an array to store some per-file information.
result = zeros(size(filelist));
for index = 1 : length(filelist)
fprintf('Processing %s\n', filelist(index).name);
% Read the sample rate Fs and store it.
[y, Fs] = wavread(filelist(index).name);
result(index) = Fs;
end
% result(1) .. result(N) contain the sample rates of each file.
An example using a cell array:
filelist = dir('*.wav');
% Pre-allocate a cell array to store some per-file information.
result = cell(size(filelist));
for index = 1 : length(filelist)
fprintf('Processing %s\n', filelist(index).name);
% Read the data of the WAV file and store it.
y = wavread(filelist(index).name);
result{index} = y;
end
% result{1} .. result{N} contain the data of the WAV files.