Automatic discrimination between files according to date - matlab

If I state my input folder in this way:
inputFolder = 'C:\myFolder\myData'
and within 'myData' there are the following files:
Car20150722.xls
Bus20150722.xls
Car20150721.xls
Bus20150721.xls
how do I specify inputFile= MODEyyyymmdd where I can specify whether the MODE is Car or Bus but it will always choose the file with the latest date.

Use dir to get a list of the file names
mode = 'Car'; %// or Bus or whatever
files = dir([mode, '*.xls']);
names = {files.name};
now extract the date, note that the date is always the 8 characters starting 12 characters from the end (and convert it to a serial date number while we're at it)
dates = cellfun(#(x)(datenum(x(end-11:end-4),'yyyymmdd')),names);
and then find the position of the max:
[~,idx] = max(dates)
and finally get the corresponding file name:
filename = names(idx)

Related

Add the date of creation to a filename in SystemVerilog

I need to create a report(.txt) and I want to reference each sessions of tests, so I wanted that for each simulations, I add the date to name of my report.
Like Report_01-19-2017-12:53.txt
So far I have been able to create either a file with the date inside with :
$system("date > sDate");
or display it on my simulation software with :
$system("date");
So far,My code look like :
string filename;
reg [8*30:1] data; // the date is of 29 characters in size
string sDate;
integer scan_file,data_file ;
initial begin
$system("date > data");
data_file = $fopen("data", "r");
scan_file = $fscanf(sDate,"%s", data);
$fclose("data");
[...]
filename = {filename,sDate};
Report_Task = $fopen(filename,"a"); [...]
end
sDate contains nothing, date contains the date...
I tried string and reg for filename and sDate
Instead of going through files to get the date, you could use svlib. Chapter 9 of the documentation illustrates how to get information about the current time.
Don't you mean
scan_file = $fscanf(data_file, "%s", sDate);
where, if the read is successful, scan_file will be equal to 1 (the number of items read). (So, you probably didn't want to call it scan_file.)

Matlab | How to load/use files with consecutive names (abc1, abc2, abc3) and then pass on to the next series (cba1, cba2, cba3)?

I have a folder containing a series of data with file names like this:
abc1
abc2
abc3
bca1
bca2
bca3
bca4
bca5
cba1
... etc
My goal is to load all the relevant files for each file name, so all the "abc" files, and plot them in one graph. Then move on to the next file name, and do the same, and so forth. Is there a way to do this?
This is what I currently have to load and run through all the files, grab the data in them and get their name (without the .mat extension) to be able to save the graph with the same filename.
dirName = 'C:\DataDirectory';
files = dir( fullfile(dirName,'*.mat') );
files = {files.name}';
data = cell(numel(files),1);
for i=1:numel(files)
fname = fullfile(dirName,files{i});
disp(fname);
files{i} = files{i}(1:length(files{i})-4);
disp(files{i});
[Rest of script]
end
You already found out about the cool features of dir, and have a cell array files, which contains all file names, e.g.
files =
'37abc1.mat'
'37abc2.mat'
'50bca1.mat'
'50bca2.mat'
'1cba1.mat'
'1cba2.mat'
The main task now is to find all prefixes, 37abc, 50bca, 1cba, ... which are present in files. This can be done using a regular expression (regexp). The Regexp Pattern can look like this:
'([\d]*[\D]*)[\d]*.mat'
i.e. take any number of numbers ([\d]*), then any number of non-numeric characters ([\D]*) and keep those (by putting that in brackets). Next, there will be any number of numeric characters ([\d]*), followed by the text .mat.
We call the regexp function with that pattern:
pre = regexp(files,'([\d]*[\D]*)[\d]*.mat','tokens');
resulting in a cell array (one cell for each entry in files), where each cell contains another cell array with the prefix of that file. To convert this to a simple not-nested cell array, we call
pre = [pre{:}];
pre = [pre{:}];
resulting in
pre =
'37abc' '37abc' '50bca' '50bca' '1cba' '1cba'
To remove duplicate entries, we use the unique function:
pre = unique(pre);
pre =
'37abc' '50bca' '1cba'
which leaves us with all prefixes, that are present. Now you can loop through each of these prefixes and apply your stuff. Everything put together is:
% Find all files
dirName = 'C:\DataDirectory';
files = dir( fullfile(dirName,'*.mat') );
files = {files.name}';
% Find unique prefixes
pre = regexp(files,'([\d]*[\D]*)[\d]*.mat','tokens');
pre = [pre{:}]; pre = [pre{:}];
pre = unique(pre);
% Loop through prefixes
for ii=1:numel(pre)
% Get files with this prefix
curFiles = dir(fullfile(dirName,[pre{ii},'*.mat']));
curFiles = {curFiles.name}';
% Loop through all files with this prefix
for jj=1:numel(curFiles)
% Here the magic happens
end
end
Sorry, I misunderstood your question, I found this solution:
file = dir('*.mat')
matching = regexp({file.name}, '^[a-zA-Z_]+[0-9]+\.mat$', 'match', 'once'); %// Match once on file name, must be a series of A-Z a-z chars followed by numbers.
matching = matching(~cellfun('isempty', matching));
str = unique(regexp(matching, '^[a-zA-Z_]*', 'match', 'once'));
str = str(~cellfun('isempty', str));
group = cell(size(str));
for is = 1:length(str)
ismatch = strncmp(str{is}, matching, length(str{is}));
group{is} = matching(ismatch);
end
Answer came from this source: Matlab Central

Batch Change File Names in Matlab

I have 200 JPEG images numbered from 1200 to 1399. How do I change their names from 1200.jpg-1400.jpg to 1.jpg-200.jpg, while keeping the original order of the image names?
This is a problem which can be tackled more efficiently in bash or other shell scripting languages. Probably, it can even be solved just via a single shell find.
Anyway, matlab can also do the job.
Consider this.
list = dir('./stack*.png'); % # assuming the file names are like stack1200.jpg
offset = -1200; # % numbering offset amount
for idx = 1:length(list) % # we go through every file name
name = list(idx).name;
number = sscanf(name,'stack%f.png',1); % # we extract the number
movefile(name,['stack' num2str(number + offset) '.png' ]); % # we rename the file.
end
I have find this solution which is quiet straightforward.
Pathfold= ('Path\to\images\');
dirData = dir('path\to\images\*.jpg');
fileNames = {dirData.name};
for i = 1:size(fileNames)
newName = sprintf('%d.jpg',i);
movefile(fileNames{i},[Pathfold , newName]) %# Rename the file
end

Creating variables with numbers from filename

I have a folder full of xls files, named data_00001 through data_10000. Each file has a dozen or so identically named tabs full of RV's. I am interested in reading all files and tabs and creating histograms of the RV's.
Is there a way to read in the last 5 digits of the file names and attached them to each tab name (which I saved as a variable)?
I used regexp to extract the number as a string and converted it to a double, and I used a for loop to save variable X{1,k}. How can I incorporate the saved double into this variable?
Are you looking for something like this?
filenames = ['data_00001','data_10000'];
nums = regexp(filenames, '[0-9]+', 'match');
tag = 'TAG';
for i=1:size(nums,2)
eval(['A_' tag '_' sprintf("%s",nums{1,i}) ' = zeros(1)']);
end
It creates matrices (zero in this case) with variable names
A_TAG_00001 = 0
A_TAG_10000 = 0

Matlab: finding/writing data from mutliple files by column header text

I have an array which I read into Matlab with importdata. It has 5 header lines
file = 'aoao.csv';
s = importdata(file,',', 5);
Matlab automatically treats the last line as the column header. I can then call up the column number that I want with
s.data(:,n); %n is desired column number
I want to be able to load up many similar files at once, and then call up the columns in the different files which have the same column header name (which are not necessarily the same column number). I want to be able to write and export all of these columns together into a new matrix, preferably with each column labelled with its file name,
what should I do?
samp = 'len-c.mp3'; %# define desired sample/column header name
file = dir('*.csv');
have the directory ready in main screen current folder. This creates a detailed description of file,
for i=1:length(file)
set(i) = importdata(file(i).name,',', 5);
end
this imports the data from each of the files (comma delimited, 5 header lines) and transports it to a cell array called 'set'
for k = 1:14;
for i=1:length(set(k).colheaders)
TF = strcmp(set(k).colheaders(i),samp); %compares strings for match
if TF == 1; %if match is true
group(:,k) = set(k).data(:,i); %save matching column# to 'group'
end
end
end
this retrieves the data from the named colheader within each file