First time here so please be gentle
So the basic idea is i have folders with just txt files that has about 20000 points each. I only want specific intervals from each of them.
I have a made a single file with the ranges for that looks like this
. 2715 2955
1132 1372
each row representing the range i want in one file
I want to batch load all the files and export the just the ranges of each. Ive lost too much sleep over this please help
dirName = '*'; %# folder path
files = dir( fullfile(dirName,'*.txt') ); %# list all *.xyz files
files = {files.name}' ; %'# file names
data = cell(numel(files),1) ; %# store file contents
for u=1:numel(files)
A=files{u} ; %# full path to file
files{u};
STR1 = A
B=load(STR1);
end
This is all i have come up with in 2 days. im new to matlab
Thanks
A very good help is the matlab help of fscanf, http://www.mathworks.co.uk/help/matlab/ref/fscanf.html. Also, in your load you don't have the path. Replace the last two lines in your for loop with:
STR1 = [dirName A]
fileID = fopen(STR1,'r');
formatSpec = '%f';
B = fscanf(fileID,formatSpec)
Or try:
delim = ' ';
nrhdr = 0;
STR1 = [dirName A]
A = importdata(STR1, delim, nrhdr);
A.data will be your data, I'm assuming no header lines.
Related
I have a problem in my code. I am using some loops in order to create mulptile .txt files with specific names, eg mR1.txt, mR2.txt,...mR100.txt. After that I merge them into one file with the following commands:
name=regexp(fileread('names.txt'), '\r?\n', 'split') .';
file1=regexp(fileread('data.txt'), '\r?\n', 'split') .';
.....
for n=1:numel(name);
for z=1:size(file1)
........ %making caluclations
FP=fopen(sprintf('mR%g0.txt',z),'wt');
fprintf(FP,'%s\t',file1{z},num2str(number),num2str(number);
fclose(FP);
txtFiles = dir('mR*.txt') ; % get the text files in the present folder
N = length(txtFiles) ; % Total number of text files
iwant = cell(N,1) ; % initlaize the data required
% loop for each file
for i = 1:N
thisFile = txtFiles(i).name ;
iwant{i} = importdata(thisFile) ; % read data of the text file
end
iwant = cell2mat(iwant) ;
outFile = strcat('finalR',num2str(n),'.txt') ;
dlmwrite(outFile,iwant,'delimiter','\t')
end
end
I would like to create for each iteration M1_mR1.txt,...,M1_mr100.txt, and M1_mR1.txt,..., M2_mR100.txt. After that I would like to merge all the files that Have prefix M1_.....txt into one file and all the files that Have prefix M2_.....txt into one file.
How could I do this?
This can be done in multiple ways.
Note about sorting: The default sorting in files will give higher value to file2 than file100, so you need to sort by actual number value. This is done by converting the filename numbers to first code and second code, and then sort by the second code with sortrows.
So this will solve the problem:
clear
textfiles_dir=dir('M*_mR*.txt');
textfiles_name={textfiles_dir.name}; %group the filenames into cell array
textfiles_codes=cellfun(#(fname)textscan(fname,'M%d_mR%d.txt'),textfiles_name,'Uniform',false);
textfiles_codes=cell2mat(cat(1,textfiles_codes{:})); %separate bw first and second code
disp(textfiles_codes)
[sorted_codes,orig_idx]=sortrows(textfiles_codes,2); %sort by second code
first_codes=sorted_codes(:,1);
second_codes=sorted_codes(:,2);
unique_firstcodes=unique(first_codes);
for ifirstcode=1:length(unique_firstcodes)
firstcode=unique_firstcodes(ifirstcode);
fprintf('firstcode=%d: ',firstcode)
target_name=sprintf('Merged%d.txt',firstcode);
f_target=fopen(target_name,'w');
idxs=orig_idx(first_codes==firstcode); % already sorted in increasing order
for i=1:length(idxs)
idx=idxs(i);
fname=textfiles_name{idx};
fprintf(' %s ',fname)
f_src=fopen(fname,'r');
src_text=fread(f_src,'*char')';
fclose(f_src);
fwrite( f_target,src_text);
end
fclose(f_target);
fprintf('\n')
end
fprintf('Done!\n')
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
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
I have some csv files that are named as:
eddypro_CFCT_201206_full_output_2013-06-26T121839.csv
eddypro_CFCT_201207_full_output_2013-06-26T160648.csv
.....
The files are mainly sorted by year and month. The characters after output are only some random numbers and letters, but the length will be same all the time.
Is there a way that i can import all these csv files together in matlab?
Part of my old code like this that can only read the files named as: eddypro_CFCT_01_full_output.csv, eddypro_CFCT_02_full_output.csv, and so on.
EddyproPath = 'C:\Users\CFCT_test\';
numfiles = length(dir([EddyproPath '\*.csv']));
for n = 1:numfiles
FilePath = [EddyproPath,'eddypro_CFCT_',num2str(n,'%02d'),'_full_output.csv'];
fid = fopen (FilePath, 'rt');
You are already using dir to get the number of files, so why not use dir to get the file list. Or am I misunderstanding?
d = dir([EddyproPath '\*.csv']);
for ii=1:numel(d),
fid = fopen(fullfile(EddyproPath,d(ii).name),'rt');
% ...
end
If for whatever reason dir is not dictionary sorting the file names, you can do sort({d.name}).
To get similar files among different text files I've used ismember()
file1 = {'DSC01605.bmp';'Hampi8.bmp';'DSC01633.bmp';...
'DSC01198.bmp';'DSC01619.bmp'}
file2 = {'DSC01605.bmp';'Hampi8.bmp';'DSC01633.bmp'}
file3 = {'DSC01605.bmp';'Hampi8.bmp'}
matching12 = ismember(file1, file2)
matching13 = ismember(file1, file3)
matchesAll3 = matching12 & matching13
allMatchingStrings = file1(matchesAll3)
Now allMatchingStrings contains
'DSC01605.bmp'
'Hampi8.bmp'
How can i write these files to a new text file all.txt? Problem with my requirements is - suppose allMatchingStrings contains around 10 files, but i need only 5 out of those 10 files. I need to save 5 files to a new text file say all.txt. How can i do that?
A quick way to write them to disk is with the fprintf command.
fid = fopen('all.txt', 'w');
fprintf(fid, '%s\n', allMatchingStrings{:});
fclose(fid);
If you only wanted to write the first 2 filenames in allMatchingStrings then you could limit like this:
filenamesIWant = 1:2;
fid = fopen('all2.txt', 'w');
fprintf(fid, '%s\n', allMatchingStrings{filenamesIWant});
fclose(fid);
This works because the fprintf command repeats for each string you give it. The only trick is getting the curly brackets int he right place.