How to load and run multiple .mat files in matlab - 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

Related

How can I save file names with consecutive numbers when saving multiple txt files in MATLAB?

I have about 2000 pieces of data that are 7611 * 1 in size. And I want to save each data as a txt file. I want to save the txt file name in 1.txt, 2.txt, 3.txt ... format, what should I do?
And additionally, when saving data, I want to keep it in 7611 * 1 format, what should I do? In this part, I will attach the code I wrote which is not work normally..
Please help. Thank you.
st = data which size is 7611*1
for i = 1:2000
data = fopen('%d.txt','w',i); % The next code doesn't work. I wrote this code
% to tell you what form I want.
fprintf(data,'%d \n',st); % I want to save as a column vector, but when I
% run it with the code next to it, the broken
% txt file is saved... I cant find reason..
end
I recommend using the sprintf command inside your for loop to create the file name, i.e.,
for i = 1:2000
fName = sprintf('%0.0f.txt',i) % create file name
data = fopen(fName,'w', ... ); % include additional specifications as needed
fprintf( ... ) % include specifications as needed
end

How to load files in a loop in matlab

I have the following operations to be done on every single file loaded in MATLAB.
A=file1
A1=A(:,4)
B=cumsum(tabletoarray(A1))
secconv=A/1000
time=datestr(C,'HH:MM:SS.FFFF')
I have 5000 .csv files in which the above operations has to be done. I need to load a file , do the operations , save the file under a new filename and repeat this for the next file. Is there a way to do this process efficiently in matlab?
You can read the files present in the folder using dir and then running a loop for each file.
files = dir('*.csv') ;
N = length(files) ; % total number of files
% loop for each file
for i = 1:N
thisfile = files(i).name ;
% Read the file using csvread
% do what you want
% save the file using save/xlswrite
end

Fast way of exporting the same figure n-times

I am trying to put together an animation in matlab. For this i am showing pictures containing a description of whats currently happening in the animation. So i am writing out pictures of my figures and later on put these together to an avi file again using matlab. For the description parts to "show up" long enough i use a simple loop in which the current figure is saved n-times. Unfortunatelly this process, though matlab does not have to calculate anything new, is the slowest one.
As the loop i use the following (h_f being the figure handle):
for delay = 1:80
export_fig (h_f,['-r' num2str(resolution)], ['C:\Users\Folder\Name_', '_' num2str(7700+delay) '.png'])
end
I just want to ask if there is any faster way. right now it kind of feels like matlab replots the fig each time before exporting it. So is there a way of plotting the figure once and simultaneously export it n-times?
Thanks for the help :)
If they are all really identical, then you can just copy the first file into the subsequent files. Your time will be limited by the speed of your disk drive and the size of your image files.
% Define some of the flags as variables. This'll make it clearer
% what you're doing when you revisit the code in a year.
% Flag for the resolution
resFlag = sprintf('-r%u', resolutions);
% Base folder
folder = 'C:\Users\Folder\';
% First file number
startnum = 7701;
% This is the pattern all the filenames will use
nameToken = 'Name_%u.png';
% First filename
firstFile = fullfile(folder, sprintf(nameToken, startnum));
% Export the first file
export_fig(h_f, resFlag, firstFile);
numCopies = 80;
% Copy the file
for delay = 2:numCopies
% Make a new filename
currentFile = fullfile(folder, sprintf(nameToken, startnum + delay));
% Copy the first file into the current filename.
copyfile(firstFile, currentFile);
end

How do I save nii files into one nii file using MATLAB

I have 360 3D-nifti files, I want to read all these files and save into one nifti file using Nifti Analyze tool that should yield a 4D file of large size. So far I have written following lines
clear all;
clc;
fileFolder=fullfile(pwd, '\functional');
files=dir(fullfile(fileFolder, '*.nii'));
fileNames={files.name};
for i=1:length(fileNames)
fname=fullfile(fileFolder,fileNames{i});
z(i)=load_nii(fname);
y=z(i).img;
temp(:,:,:,i) = make_nii(y);
save_nii(temp(:,:,:,i), 'myfile.nii')
fprintf('Iter: %d\n', i)
end
This code facilitates with a variable temp that is 4D struct and contains all the images. However, myfile.nii is just one single file its not all the images because its size is just 6mb it should be atleast one 1gb.
Can someone please have a look and let me know where I am wrong?
The way that you have it written, your loop is overwriting myfile.nii since you're calling save_nii every time through the loop with only the latest data. You'll want to instead call save_nii only once outside of the loop and save the entire temp variable at once.
for k = 1:numel(fileNames)
fname = fullfile(fileFolder, fileNames{k});
z(k) = load_nii(fname);
y(:,:,:,k) = z(k).img;
end
% Create the ND Nifti file
output = make_nii(y);
% Save it to a file
save_nii(output, 'myfile.nii')

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.