inserting headline in matlab exporting file - matlab

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);

Related

Reading Text file comma seperated on Matlab

I'm trying to read a comma separated text file that looks like the following:
2017-10-24,01:17:38,2017-10-24,02:17:38,+1.76,L,Meters
2017-10-24,02:57:31,2017-10-24,03:57:31,+1.92,H,Meters
2017-10-24,05:53:35,2017-10-24,06:53:35,+1.00,L,Meters
2017-10-24,10:45:01,2017-10-24,11:45:01,+2.06,H,Meters
2017-10-24,13:27:16,2017-10-24,14:27:16,+1.78,L,Meters
2017-10-24,15:07:16,2017-10-24,16:07:16,+1.92,H,Meters
2017-10-24,18:12:08,2017-10-24,19:12:08,+0.98,L,Meters
My code so far is:
LT_data = fopen('D:\Beach Erosion and Recovery\Bournemouth\Bournemouth Tidal Data\tidal_data_jtide.txt');% text file containing predicted low tide times
LT_celldata = textscan(LT_data,'%D %D %D %D %d ','delimiter',',')'
For mixed data types, I'd recommend readtable. This will read your data straight into a table object without having to specify a format spec or use fopen,
t = readtable( 'myFile.txt', 'ReadVariableNames', false, 'Delimiter', ',' );
Then you can easily manipulate the data
% Variable names in the table
t.Properties.VariableNames = {'Date1', 'Time1', 'Date2', 'Time2', 'Value', 'Dim', 'Units'};
% Create full datetime object columns from the date and time columns
t.DateTime1 = datetime( strcat(t.Date1,t.Time1), 'InputFormat', 'yyyy-MM-ddHH:mm:ss' );
If you do know the formats, you can specify the 'format' property within readtable and it will convert the data when reading.
This is working perfectly. The formatspec need to be edited.
file = 'D:\Beach Erosion and Recovery\Bournemouth\Bournemouth Tidal Data\tidal_data_jtide.txt'
fileID = fopen(file);
LT_celldata = textscan(fileID,'%D%D%D%D%d%[^\n\r]','delimiter',',')

Read data to matlab with for loop

I want to read the data of a file with size about 60 MB into matlab in some variables, but I get errors. This is my code:
clear all ;
clc ;
% Reading Input File
Dataz = importdata('leak0.lis');
%Dataz = load('leak0.lis');
for k = 1:1370
foundPosition = 1 ;
for i=1:size(Dataz,1)
strp = sprintf('I%dz=',k);
fprintf(strp);
findValue = strfind(Dataz{i}, strp) ;
if ~isempty(findValue)
eval_param = strp + '(foundPosition) = sscanf(Dataz{i},''%*c%*c%*f%*c%*c%f'') ;';
disp(eval_param);
% str(foundPosition) = sscanf(Dataz{i},'%*c%*c%*f%*c%*c%f') ;
eval(eval_param);
foundPosition = foundPosition + 1 ;
end
end
end
When I debugged it, I found out that the dataz is empty & so it doesn't proceed to next lines. I replace it with fopen, load & etc, but it didn't work.
From the Matlab help files, import data is likely failing because it doesn't understand your file format.
From the help files
Name and extension of the file to import, specified as a string. If importdata recognizes the file extension, it calls the MATLAB helper function designed to import the associated file format (such as load for MAT-files or xlsread for spreadsheets). Otherwise, importdata interprets the file as a delimited ASCII file.
For ASCII files and spreadsheets, importdata expects to find numeric
data in a rectangular form (that is, like a matrix). Text headers can
appear above or to the left of the numeric data, as follows:
Assuming that your .lis files actually have delimited text.
You should adjust the delimiter in the importdata call so that Matlab can understand your file.
filename = 'myfile01.txt';
delimiterIn = ' ';
headerlinesIn = 1;
A = importdata(filename,delimiterIn,headerlinesIn);

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

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');

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!

saving common strings to a new text file in MATLAB

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.