I try to skip lines 5 to the end of the file from a .txt-file I import into Matlab.
fidM = fopen('abc.txt', 'r');
for i = 5:150
fgetl(fidM);
end
buffer = fread(fidM, Inf) ;
fclose(fidM);
fidM = fopen('xyz.txt', 'w');
fwrite(fidM, buffer) ;
fclose(fidM) ;
The code above does not do the job somehow. Any ideas?
Your code currently reads the first 146 lines of your file, discards them, then reads the remainder and writes that out to a file. Instead, if you want to just write the first 5 lines of abc.txt into xyz.txt, then do something like the following:
fid = fopen('abc.txt', 'r');
fout = fopen('xyz.txt', 'w');
for k = 1:5
fprintf(fout, '%s\r\n', fgetl(fid));
end
fclose(fid);
fclose(fout);
Or you can remove the loop and do something like this:
fid = fopen('abc.txt', 'r');
% Read in the first 5 lines
contents = textscan(fid, '%s', 5);
fclose(fid);
% Write these to a new file
fout = fopen('xyz.txt', 'w');
fprintf(fout, '%s\r\n', contents{1}{:});
fclose(fout);
Related
I read a .txt file into a 1x1 cell array using textscan. How to I extract certain data from that 1x1 cell array?
The .txt file has mixed format data.
The code I have so far:
%% Import Safir output file
FileName="PROOV_6.txt";
tic
%% Read the txt file
FID = fopen(FileName, 'r');
if FID == -1
error('Cannot open file')
end
Data = textscan(FID, '%s', 'delimiter', '\n', 'whitespace', ' ' );
CStr = Data{1};
fclose(FID);
%% Find all row numbers that contain the string
Index = strfind(CStr, 'TOTAL TEMPERATURES');
IndexA = find(not(cellfun('isempty', Index)));
%% Loop through CStr accessing matrices between strings "TOTAL TEMPERATURES"
%% ----------
%% Save the file again
FID = fopen(FileName, 'w');
if FID == -1
error('Cannot open file')
end
fprintf(FID, '%s\n', CStr{:});
fclose(FID);
toc
I will also provide a link to the .txt file:
PROOV_6.txt
Use {} indexing to get a value out of a cell array. That there is only one cell makes no difference. mycell{1}.
Matlab help: I am trying to export all 50 points to a CSV. How can I append the csv files after each iteration?
%import csv file
filename = 'Q:\Electroporation\raw_works.csv';
delimiter = ',';
startRow = 2;
%% Format for each line of text:
formatSpec = '%s%f%f%f%f%f%f%f%f%f%[^\n\r]';
%% Open the text file.
fileID = fopen(filename,'r');
%% Read columns of data according to the format.
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'TextType', 'string', 'HeaderLines' ,startRow-1, 'ReturnOnError', false, 'EndOfLine', '\r\n');
%% Close the text file.
fclose(fileID);
%% Create output variable
rawworks = table(dataArray{1:end-1}, 'VariableNames', {'Name','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'});
%% Clear temporary variables
clearvars filename delimiter startRow formatSpec fileID dataArray ans;
So far the data in MATLAB.
% store data into a variable
table= rawworks;
array=str2double(table2array(table)); % convert to array
ss= size(array)
N= ss(1)
ones=ones(50,14);
xls=zeros(50,14);
Now I do the math operation
for i= 1:N
A=[array(i,2) array(i,3) array(i,4);array(i,5) array(i,6) array(i,7);array(i,8) array(i,9) array(i,10)];
%diognalize
[U,S,V]=svd(A);
P1=S(1,1);
P2=S(2,2);
P3=S(3,3);
%output data
data_for_excel_file=[A(1,1) A(1,2) A(1,3) A(2,1) A(2,2) A(2,3) A(3,1) A(3,2) A(3,3) P1 P2 P3 P1/P2 P1/P3 ]
here is where I'm having problems. How can I make csvwrite append to the end of % file. Currently, it is only writing out the last result instead of all 50.
csvwrite('Diognalized_output.csv',data_for_excel_file,1) %HELP
end
If you are okay using the more general function dlmwrite instead, you can use its -append flag to add your output to the end of the file each time.
Change your last line from
csvwrite('Diognalized_output.csv',data_for_excel_file,1)
to
dlmwrite('Diognalized_output.csv,data_for_excel_file,'-append')
The default delimiter for dlmwrite is the comma (,) so you get the same output format here.
I have a text file, suppose myfile.txt, that stores floating point coordinates in following manner:
53
-464.000000 -20.000000 0.009000
-464.000000 -17.000000 0.042000
-464.000000 -13.000000 0.074000
-464.000000 -11.000000 0.096000
-464.000000 -8.000000 0.114000
...
...
...
42
380.000000 193.000000 7.076000
381.000000 190.000000 7.109000
383.000000 186.000000 7.141000
384.000000 184.000000 7.163000
384.000000 183.000000 7.186000
386.000000 179.000000 7.219000
...
...
...
the first line specifies the number of lines for the first set of coordinates, followed by that many lines. and then theres is another integer specifying the the number of lines for the next set of coordinates.
i.e. 1st line has 53, so next 53 lines are 1st set of coords(ending at line 54). Then line 55 has value 42, so next 42 lines are 2nd set of coords.
How can I read the text file such that i read 1st line, and the next 53 lines are read and stored in matrix. Then read 42 and the next 42 lines are read and stored? The text file is like this until EOF.
You could do it with Low-Level File I/O, like this:
fid = fopen('myfile.txt', 'r');
matrix = {};
while ~feof(fid)
N = fscanf(fid, '%d\n', 1);
matrix{end + 1} = fscanf(fid, '%f\n', [3 N])';
end
fclose(fid);
fid = fopen('myfile.txt ', 'r');
ind = 1;
mycell = {};
while ~feof(fid)
N = fscanf(fid, '%d\n', 1);
matrix = fscanf(fid, '%f\n', [3 N]);
matrix = transpose(matrix);
cell{ind} = matrix;
ind = ind + 1;
end
fclose(fid);
My two cents:
function matrix_cells = import_coordinates(filename, startRow, endRow)
%IMPORT_COORDINATES Import numeric data from a text file as a matrix.
% MATRIX_CELLS = IMPORT_COORDINATES(FILENAME) Reads data from text file FILENAME
% for the default selection and store it into the array of cells MATRIX_CELLS.
%
% MATRIX_CELLS = IMPORT_COORDINATES(FILENAME, STARTROW, ENDROW) Reads data from
% rows STARTROW through ENDROW of text file FILENAME.
%
% Example:
% matrix_cells = import_coordinates('coordinates.txt', 1, 15);
%
% See also TEXTSCAN.
%% Initialize variables.
delimiter = ' ';
if nargin<=2
startRow = 1;
endRow = inf;
end
%% Format string for each line of text:
% column1: double (%f)
% column2: double (%f)
% column3: double (%f)
% For more information, see the TEXTSCAN documentation.
formatSpec = '%f%f%f%[^\n\r]';
%% Open the text file.
fileID = fopen(filename,'r');
%% Read columns of data according to format string.
% This call is based on the structure of the file used to generate this
% code. If an error occurs for a different file, try regenerating the code
% from the Import Tool.
dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'EmptyValue' ,NaN,'HeaderLines', startRow(1)-1, 'ReturnOnError', false);
for block=2:length(startRow)
frewind(fileID);
dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'EmptyValue' ,NaN,'HeaderLines', startRow(block)-1, 'ReturnOnError', false);
for col=1:length(dataArray)
dataArray{col} = [dataArray{col};dataArrayBlock{col}];
end
end
%% Close the text file.
fclose(fileID);
%% Post processing for unimportable data.
% No unimportable data rules were applied during the import, so no post
% processing code is included. To generate code which works for
% unimportable data, select unimportable cells in a file and regenerate the
% script.
%% Create output variable
matrix_temp = [dataArray{1:end-1}];
%% MY CONTRIBUTION ;)
% find rows with nan values
[i,~]=find(isnan(matrix_temp));
indexes=unique(i);
%% Create output cell array
matrix_cells=cell(numel(indexes),1);
%% Fill cell array filtering out unuseful rows and parting original matrix
for i=1:1:numel(indexes)-1
matrix_cells{i}=matrix_temp(indexes(i)+1:indexes(i+1)-1,:);
end
% Last matrix
matrix_cells{end}=matrix_temp(indexes(end)+1:size(matrix_temp,1),:);
The first part (reading and import of text file) of this function was autogenerated by MATLAB. I added only the code to split and save the matrix into a cell array.
I assume that coordinates do not contain nan values; morevoer, I do not check for consistency between the declared number of rows and the actual one for each block.
Here an example; the following is the file coordinates.txt
5
-464.000000 -20.000000 0.009000
-464.000000 -17.000000 0.042000
-464.000000 -13.000000 0.074000
-464.000000 -11.000000 0.096000
-464.000000 -8.000000 0.114000
3
380.000000 193.000000 7.076000
381.000000 190.000000 7.109000
383.000000 186.000000 7.141000
2
384.000000 184.000000 7.163000
384.000000 183.000000 7.186000
1
386.000000 179.000000 7.219000
Excute the function:
coordinate_matrices=import_coordinates('coordinates.txt')
coordinate_matrices =
[5x3 double]
[3x3 double]
[2x3 double]
[1x3 double]
This is the content of every cell:
>> coordinate_matrices{1}
ans =
-464.0000 -20.0000 0.0090
-464.0000 -17.0000 0.0420
-464.0000 -13.0000 0.0740
-464.0000 -11.0000 0.0960
-464.0000 -8.0000 0.1140
>> coordinate_matrices{2}
ans =
380.0000 193.0000 7.0760
381.0000 190.0000 7.1090
383.0000 186.0000 7.1410
>> coordinate_matrices{3}
ans =
384.0000 184.0000 7.1630
384.0000 183.0000 7.1860
>> coordinate_matrices{4}
ans =
386.0000 179.0000 7.2190
I am trying to read a .csv file in matlab and saving it as .txt. but it seems that when i print the lines in my .txt file, the line is nothing:
fid1 = fopen('input.csv');
fid = fopen('output.txt', 'w');
tline = fgetl(fid1);
tline = strrep(tline,'remove','')
fprintf(fid, '%s\n', tline);
fclose(fid1);
fclose(fid);
when i open the file afterwards the file is empty
if i convert the .csv file to .txt using excell there is no problem.
how do i easily convert the .csv data into .txt?
i can't do it manually because i have hundreds of .csv files
I think you are not processing every line of your csv file (if the first line is empty it explains your empty txt files).
fid1 = fopen('test.csv');
fid = fopen('output.txt', 'w');
tline = fgetl(fid1);
while ischar(tline)
tline = strrep(tline,'remove','');
fprintf(fid, '%s\n', tline);
tline = fgetl(fid1);
end
fclose(fid1);
fclose(fid);
below is the program which generates random data and converts it into 0's and 1's and saves them in .dat file in matlab every 5 minutes
every time it overwrites the data with existing data
how to generate different data for every 5 minutes and then save each data seperately?
is it possible?
while(1)
tic
A = rand(1,5)
disp(A);
File_id = fopen('delay.dat', 'w');
fwrite(File_id, A, 'double');
fclose(File_id);
File_id = fopen('test.dat', 'r');
A = fread(File_id,'double=>int8');
fclose(File_id);
disp(A);
T=toc;
pause(300-T)
end
As Mohammad said in the comments, you should change the name of the output file in each iteration:
i = 0;
while(1)
i=i+1;
tic
A = rand(1,5)
disp(A);
File_id = fopen(['delay_' str(i) '.dat'], 'w');
fwrite(File_id, A, 'double');
fclose(File_id);
File_id = fopen('test.dat', 'r');
A = fread(File_id,'double=>int8');
fclose(File_id);
disp(A);
T=toc;
pause(300-T)
end