I want to read all wav files containing in a folder and save samples of each file in several cvs files containing in other folder.
This is my code:
dirMask = 'inputFolder\*.wav';
wavRoot = fileparts(dirMask);
Files=dir(dirMask);
for k=1:length(Files)
FileNames = fullfile(wavRoot, Files(k).name);
[s,fs] = audioread(FileNames);
end
fid = fopen('\filename.xls','a');
fprintf(fid,'%f\n',num2str(s));
fclose(fid);
This code doesn't work. How can I do this?
Firstly, note that you are using %f which is for floats, but you are converting "s" into a string. Also, \n jumps to the next line, so if you need several columns you will have to check when to use \n or \t (tab) or just ";" for example. Check matlab data formatting in any case
So if you know the exact number of columns (e.g. 3 columns) you can write:
fprintf(fid,'%s \t %s \t %s \n',string1, string2, string3);
If you want to do it within a loop you can check your iterator and add "\n" every X strings.
E.g.
ncols = 3
for i = 1:21
mystring = num2str(i)
if mod(i,ncols) == 0
fprintf(fid,'%s \n',mystring);
else
fprintf(fid,'%s ', mystring);
end
end
Related
I have a text file containing randoms of 0 and 1, and I want to read it in Matlab and obtain each element in an array
goal :
I have two text files that I want to compare and see if they are identical and how much difference there is, in fact, the two files are :
1) original file that I send via a communication line
2) the received file should be identical to the send file
Example of my code:
for i=1:1:size
if (send[i] ~= received[i]) error++;
end
but I need to know how to obtain these two arrays from the text files, where all the "0" and "1" are in one line
Since you want to check that the contents of the two files are the same, I do not think you need to worry about the format of their contents or the sequence of zeros and ones, they should be simply identical. You can use the following code to read the entire text file and store it in a char vector:
C = char(join(readlines(filename), ''));
To compare contents of two files and find the error percent you can do the following:
act = char(join(readlines(actualfilename), ''));
exp = char(join(readlines(expectedfilename), ''));
err = (sum(act~=exp))/length(act);
But you should also detect if two files contain different number of characters:
act = char(join(readlines(actualfilename), ''));
exp = char(join(readlines(expectedfilename), ''));
al = length(act); % actual length
el = length(exp); % expected length
dl = abs(al-el);
if (dl>0)
ml = min(al, el); % min length
act = act(1:ml); % shorten act if needed
exp = exp(1:ml); % shorten exp if needed
end
err = (sum(act~=exp)+dl)/al % error
Note that in the second case, if a character is added or lost in the middle of the file, all subsequent characters will be considered as error.
Reading in the Text Files:
If the text file is configured with spaces or line breaks:
Text.txt (line breaks)
0
1
0
1
1
Text.txt (spaces)
1 0 1 0 1 1
Scanning in the data can be done by using the fscanf() function with format specification %d indicated to scan in the file as integers.
File_Name = "Text.txt";
File_ID = fopen(File_Name);
Binary = fscanf(File_ID,'%d');
If the text file has the characters beside/concatenated on the same line without spaces:
Text.txt (single line, no spaces)
01011
Scanning the text file can be done using the format specification, %s indicated to read the file as a string. This string can be split and converted into an array by using split(), cell2mat() and str2num().
split() → Splits the string into a cell array with individual bits/binary
cell2mat() → Converts the cell array to a character array
str2num() → Converts the character array to a numerical double array
File_Name = "Text.txt";
File_ID = fopen(File_Name);
Binary = fscanf(File_ID,'%s');
Binary = split(Binary,'');
Binary = str2num(cell2mat(Binary(2:end-1))).';
Comparing to Evaluate Amount of Errors:
Error checking can be done by comparing the arrays logically in an element-wise fashion. Then by using the nnz() (number of non-zeroes) function we can count the number of times the condition is true, "1". Here the condition is when the two binary signals Binary_1 and Binary_2 not equal to each other.
Code Snippet:
Error = nnz(Binary_1 ~= Binary_2);
Error
Full Script Option 1 (line breaks/spaces text file):
File_Name = "Text_1.txt";
File_ID = fopen(File_Name);
Binary_1 = fscanf(File_ID,'%d');
fclose(File_ID);
File_Name = "Text_2.txt";
File_ID = fopen(File_Name);
Binary_2 = fscanf(File_ID,'%d');
fclose(File_ID);
clearvars -except Binary_1 Binary_2
Error = nnz(Binary_1 ~= Binary_2);
Error
Full Script Option 2 (single line, no spaces text file):
File_Name = "Text_1.txt";
File_ID = fopen(File_Name);
Binary_1 = fscanf(File_ID,'%s');
Binary_1 = split(Binary_1,'');
Binary_1 = str2num(cell2mat(Binary_1(2:end-1))).';
File_Name = "Text_2.txt";
File_ID = fopen(File_Name);
Binary_2 = fscanf(File_ID,'%s');
Binary_2 = split(Binary_2,'');
Binary_2 = str2num(cell2mat(Binary_2(2:end-1))).';
fclose(File_ID);
clearvars -except Binary_1 Binary_2
Error = nnz(Binary_1 ~= Binary_2);
Error
Ran using MATLAB R2019b
I am trying to concatenate three lines (I want to leave the lines as is; 3 rows) from Shakespeare.txt file that shows:
To be,
or not to be:
that is the question.
My code right now is
fid = fopen('Shakespeare.txt')
while ~feof(fid)
a = fgets(fid);
b = fgets(fid);
c = fgets(fid);
end
fprintf('%s', strcat(a, b, c))
I'm supposed to use strcat and again, I want concatenated and leave them as three rows.
One method of keeping the rows separate is by storing the lines of the text file in a string array. Here a 1 by 3 string array is used. It may also be a good idea to use fgetl() which grabs each line of the text file at a time. Concantenating the outputs of fgetl() as strings may also be another option to ensure the they do not get stored as character (char) arrays. Also using the \n indicates to line break when printing the strings within the array String_Array.
fid = fopen('Shakespeare.txt');
while ~feof(fid)
String_Array(1) = string(fgetl(fid));
String_Array(2) = string(fgetl(fid));
String_Array(3) = string(fgetl(fid));
end
fprintf('%s\n', String_Array);
Ran using MATLAB R2019b
I would like to plot a number of 3D graphs from different data files. For example I am using
fid = fopen('SS 1.dat','r');
to read the first file and then plot a graph. How to set the program to change the name to 'SS 2.dat' automatically? Also for the tenth file the name becomes 'SS 10.dat' which has one space less (i.e.only two space between SS and 10) then the first to ninth files. How to set the program to adjust for that? Thank you.
Use dir:
filenames = dir('*.dat'); %//gets all files ending on .dat in the pwd
for ii =1:length(filenames)
fopen(filenames(ii),'r');
%//Read all your things and store them here
end
The beauty of dir as opposed to the other solutions here is that you can get the contents of the pwd (present working directory) in one single line, regardless of how you called your files. This makes for easier loading of files, since you do not have any hassle with dynamic file names.
The following code displays a lazy way to print the names from 1 to 999 that you mentioned:
for ii=1:999
ns = numel(num2str(ii));
switch ns
case 1
fname = ['ss ' num2str(ii) '.dat'];
case 2
fname = ['ss ' num2str(ii) '.dat'];
case 3
fname = ['ss ' num2str(ii) '.dat'];
end
end
Another way:
is to use the backslash character in the formatting of the filename as follows:
fstr = 'ss ';
for ii = 1:999
ns = numel(num2str(ii));
for jj = 1:ns-1
fstr = [fstr '\b'];
end
ffstr = sprintf(fstr);
fname = [ffstr num2str(ii) '.dat'];
disp(fname);
end
there are many better ways to do this though
prefix = 'SS';
for n = 1:10
if n == 10
filename = [prefix ' ' num2str(n) '.dat'];
else
filename = [prefix ' ' num2str(n) '.dat'];
end
fid = fopen(filename, 'r');
...
end
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.
I want help in reading all the text files at the same time and also splitting the text to be stored into an array. I have tried for this but was not able to do so. The main problem occurring is that even while using for loop for reading text file the strsplit splits only one text file. How can i split all of them at once into different arrays, means one array for one text file.
Below is the code so far-
for i = 1:10
file = [num2str(i) '.eng'];
% load string from a file
STR = importdata(file);
% extract string between tags
B = regexprep(STR, '<.*?>','');
% split each string by delimiters and add to C
C = [];
for j=1:length(B)
if ~isempty(B{j})
C = [C strsplit(B{j}, {'/', ' '})];
end
end
Below is sample of text file---
<DOC>
<DOCNO>annotations/01/1515.eng</DOCNO>
<TITLE>Yacare Ibera</TITLE>
<DESCRIPTION>an alligator in the water;</DESCRIPTION>
<NOTES></NOTES>
<LOCATION>Corrientes, Argentina</LOCATION>
<DATE>August 2002</DATE>
<IMAGE>images/01/1515.jpg</IMAGE>
<THUMBNAIL>thumbnails/01/1515.jpg</THUMBNAIL>
</DOC>
Suppose you are looking for the word "alligator". Then you could do the following
clc
word = 'alligator';
num_of_files = 10;
C = cell(num_of_files, 1);
for i = 1:10
file = [num2str(i) '.eng'];
%// load string from a file
STR = importdata(file);
%// extract string between tags
%// assuming you want to remove the angle brackets
B = regexprep(STR, '<.*?>','');
B(strcmp(B, '')) = [];
%// split each string by delimiters and add to C
tmp = regexp(B, '/| ', 'split');
C{i} = [tmp{:}];
end
where = [];
for j = 1:length(C)
if find(strcmp(C{j}, word))
where = [where num2str(j) '.eng, '];
end
end
if length(where) == 0
disp(['No file contains the word ' word '.'])
else
where(end-1:end) = [];
disp(['The word ' word ' is contained in: ' where])
end
Because I used 10 copies of your file, the word "alligator" is in each one of them so I get
The word alligator is contained in: 1.eng, 2.eng, 3.eng, 4.eng, 5.eng,
6.eng, 7.eng, 8.eng, 9.eng, 10.eng
Whereas, if I set word = 'cohomology', the output is
No file contains the word cohomology.