How can I write out header names along with data using dlmwrite? - matlab

I use this code to write out to a csv file inside a loop. The loop will run thousands of times and store these 5 data points after every run.
dlmwrite('test.csv', [outlet_info.outlet_row, outlet_info.outlet_col,
outlet_info.rel_err, outlet_info.new_est_darea, delta1)
How can I put header names in the csv file as well? eg. row, col, err, area, del
How can I append 5 new data as a new row after every loop? How do I use append?

Use fprintf to write the header as a single line into the file.
Then use dlmwrite to append data to it:
filename = 'test.csv';
fid = fopen(filename, 'w');
fprintf(fid, 'HEADER LINE HERE...\n');
fclose(fid)
for i = ... %(loop over your data here...)
dlmwrite(filename, [outlet_info.outlet_row, outlet_info.outlet_col,
outlet_info.rel_err, outlet_info.new_est_darea, delta1], '-append', 'precision', '%.6f', 'delimiter', ';');
end

You can also do this with using dlmwrite only. Just write the header first an then use the -append flag to append to it:
%prepare your header string
hdr = 'row, col, err, area, del';
%write header first
dlmwrite('test.csv', hdr, '');
%append your data to the same file
dlmwrite('test.csv', [outlet_info.outlet_row, outlet_info.outlet_col,
outlet_info.rel_err, outlet_info.new_est_darea, delta1, '-append');

Related

Matlab Error: ()-indexing must appear last in an index expression

I have this code and want to write an array in a tab delimited txt file :
fid = fopen('oo.txt', 'wt+');
for x = 1 :length(s)
fprintf(fid, '%s\t\n', s(x)(1)) ;
end;
fclose(fid);
but I receive this error :
Error: ()-indexing must appear last in an index expression.
how should i call s(x)(1)? s is an array
s <2196017x1 cell>
when I use this code I get no error but return me some characters not words.
fprintf(fid, '%s\t\n', ( s{x}{1})) ;
With MATLAB, you cannot immediately index into the result of a function using () without first assigning it to a temporary variable (Octave does allow this though). This is due to some of the ambiguities that happen when you allow this.
tmp = s(x);
fprintf(fid, '%s\t\n', tmp(1)) ;
There are some ways around this but they aren't pretty
It is unclear what exactly your data structure is, but it looks like s is a cell so you should really be using {} indexing to access it's contents
fprintf(fid, '%s\t\n', s{x});
Update
If you're trying to read individual words in from your input file and then write those out to a tab-delimited file, I'd probably do something like the following:
fid = fopen('input.txt', 'r');
contents = fread(fid, '*char')';
fclose(fid)
% Break a string into words and yield a cell array of strings
words = regexp(contents, '\s+', 'split');
% Write these out to a file separated by tabs
fout = fopen('output.tsv', 'w');
fprintf(fout, '%s\t', words{:});
fclose(fout)

Insert String in a CSV file matlab

how do I insert a string into a csv file in matlab. i used this code to write some data and create my csv file:
and here is the output of the code:
I'm trying to insert some text in the first 2 columns before the numerical data..
thanks in advance :)
There are several approaches are possible here.
Let's take a look at some of them:
If you need to add string to your csv file.
For example, I create some csv file like your:
q = [1 2 3 4 5 6 7];
csvwrite('csvlist4.csv',q,2,0);
All troubles is to add some string to csv - it's because we need to combine numeric and text data. There are no good functions for it in Matlab except low levels:
c = 'some big text';
fid = fopen('csvlist4.csv','r+');
fprintf(fid,c);
How it works: the data in csv is an array. I put data in 3rd row, so first and second is an empty but they have ','. When you use fprintf it will replace this , with your text. So if text is too long it will overwrite your data.
How to avoid this?
Easiest way - is to do it with help of xlswrite function. For your example:
txt = cell(size(Q))
txt{1} = 'this is your text'
X = [txt; num2cell(Q)]
xlswrite('new.xlsx',X)
Result:
Important moment here: number of cell for text must be the same as your data. But I filled with the text only first cell in my example.
And the one more way: read csv file, modify it's data and write to csv:
csvwrite('csvlist4.csv',a,2,0);
m = csvread('csvlist4.csv');
fid = fopen('csvlist4.csv','w');
c = 'your text'
fprintf(fid, c); fprintf(fid, '\n');
fclose(fid);
dlmwrite('csvlist4.csv', m(3:end,:), '-append');
Of course you can use cell array instead c and so on and so on.
Hope it helps!

Read file names from .txt file in MATLAB

I am attempting to read in multiple file names from a .txt file. Each file names has multiple spaces and ends in different file formats.
When I try this code
M = textread('playlist.m3u', '%s')
I get the results to be the first string in the first row followed by the next string after the space is the next row ect.
One of the file names in the text file is "C:\Users\user\Music\Pink Floyd\Wish You Were Here (Matersound Gold Limited Edition)\03 - Have a Cigar.flac"
'C:\Users\user\Music\Pink'
'Floyd\Wish'
'You'
'Were'
'Here'
'(Matersound'
'Gold'
'Limited'
'Edition)\03'
'-'
'Have'
'a'
'Cigar.flac'
How do I simply read in all the files with each file taking up 1 cell in an cell array?
Use textscan and specify newline \n as the delimiter:
fid = fopen('playlist.m3u');
M = textscan(fid, '%s', 'delimiter', '\n')

inserting headline in matlab exporting file

I have a matrix (input) and want to export it as a text file (output), therefore, I am using the following code in matlab:
save('out.txt', 'input', '-ASCII');
My question is that how I can insert for example 3 lines (as follow) for its header? I don't want to open the output.txt file in another program, because the size of the output.txt is very large and non of the available softwar can open it. Therefore, I want to do this directly in matlab.
These data set are...
It is created by
2013
I think you cannot do it using only save function. For a quick, I can see two options that might be useful.
First. Create a file with the header and then use save with -append options:
input = rand(5);
header = ['These data set are It is created by 2013'];
fileID = fopen('out.txt','w');
fprintf(fileID,'%s\n', header);
fclose(fileID);
save('out.txt', 'input', '-ASCII', '-append');
Second. Instead of using save, manually use fprintf to write everything:
input = rand(5);
header = ['These data set are It is created by 2013'];
fileID = fopen('out.txt','w');
fprintf(fileID,'%s\n', header);
fprintf(fileID,[repmat('%f ', [1, size(input, 2)]),'\n'], input);
fclose(fileID);
If u want multi-line header, u can do as follows:
header = ['These data set are ...\nIt is created by\n2013'];
fileID = fopen('out.txt','w');
fprintf(fileID, [header, '\n']);
fprintf(fileID,[repmat('%f ', [1, size(input, 2)]),'\n'], input);
fclose(fileID);

Replace wordA to wordB in a txt and then save it in a new file. MATLAB

How could I write a function to take in the following:
filename: (a string that corresponds to the name of a file)
wordA and wordB: They are both two strings with no space
The function should do this:
A- read the a txt file line by line
B- replace every occurrence of wordA to wordB.
C- Write the modifified text file with the same as the original file, but preprended with 'new_'. For instance, if the input file name was 'data.txt', the output would be 'new_data.txt'.
Here is what I have done. It has so many mistakes but I got the main idea. Could you please help to find my mistake and to make the function work.
function [ ] = replaceStr( filename,wordA, wordB )
% to replace wordA to wordB in a txt and then save it in a new file.
newfile=['new_',filename]
fh=fopen(filename, 'r')
fh1=fgets(fh)
fh2=fopen(newfile,'w')
line=''
while ischar(line)
line=fgetl(fh)
newLine=[]
while ~isempty(line)
[word line]= strtok(line, ' ')
if strcmp(wordA,wordB)
word=wordB
end
newLine=[ newLine word '']
end
newLine=[]
fprintf('fh2,newLine')
end
fclose(fh)
fclose(fh2)
end
You can read the entire file in a string using the FILEREAD function (it calls FOPEN/FREAD/FCLOSE underneath), substitute text, then save it all at once to a file using FWRITE.
str = fileread(filename); %# read contents of file into string
str = strrep(str, wordA, wordB); %# Replace wordA with wordB
fid = fopen(['new_' filename], 'w');
fwrite(fid, str, '*char'); %# write characters (bytes)
fclose(fid);
Some things to fix:
It will be much easier to use the function STRREP instead of parsing the text yourself.
I would use FGETS instead of FGETL to keep the newline character as part of the string, since you will want to output them to your new file anyway.
The format of your FPRINTF statement is all wrong.
Here's a corrected version of your code with the above fixes:
fidInFile = fopen(filename,'r'); %# Open input file for reading
fidOutFile = fopen(['new_' filename],'w'); %# Open output file for writing
nextLine = fgets(fidInFile); %# Get the first line of input
while nextLine >= 0 %# Loop until getting -1 (end of file)
nextLine = strrep(nextLine,wordA,wordB); %# Replace wordA with wordB
fprintf(fidOutFile,'%s',nextLine); %# Write the line to the output file
nextLine = fgets(fidInFile); %# Get the next line of input
end
fclose(fidInFile); %# Close the input file
fclose(fidOutFile); %# Close the output file