How to save several times without overwriting the file - matlab

I have a problem with my code in matlab.
I have a matrix C (make reshape as a vector) and I want to save several C vectors to one file. This is my code
wynik = reshape(C',1,[]);
fileID = fopen('Desktop\test.txt','r');
fileID_out = fopen('Desktop\test_out.txt','r');
fprintf(fileID, '%d \r', wynik);
fprintf(fileID, '\n');
fprintf(fileID_out, ' %d \r\n', 2);
end
I made a loop at the begin so in a console I have for example 2 different matrix, but using this code it overwrite my file and I save only the last one vector. I would like to have sth like this (shorter example)
A = [ 1 2 3; 4 5 6 ] ( first loop)
A = [7 8 9; 1 2 3 ] ( second loop)
In my file(with spaces between values and with \n on the end of line) :
1 2 3 4 5 6
7 8 9 1 2 3

The example in your question is quite unclear because you ask about saving data but all your file opening instructions use only reading permissions.
I'll give you an example which works for your 2nd (shorter) example because it is clearer what you are trying to achieve.
I strongly recommend to read the documentation for:
fopen, and particularly the usage of the parameter permission.
fprintf the the parameter formatSpec will be useful.
Armed with that documentation, you will realise that to write to an existing file already containing data is called append to the file. So for your usage: The first time you create the file, open it with the permission 'w'. For all the other time you want to add (=append) something to the file, open it with the permission 'a', then write normally to it.
Your second example in code:
%% Initial data
A = [1,2,3;4,5,6];
%% prepare format specifier for a complete line
nElem = numel(A) ;
baseformat = '%d ' ; % base number format
writeFormat = repmat( baseformat , 1 , nElem ) ; % replicated "nElem" times
writeFormat = [writeFormat(1:end-1) '\n'] ; % remove last trailing space and replace by newline
% => now writeFormat = "%d %d %d %d %d %d\n"
%% Open the file the first time to write the first line
% permission 'w' => Open or create new file for writing. Discard existing contents, if any.
fidout = fopen('myfileout.txt', 'w') ;
fprintf( fidout , writeFormat , A(:) ) ;
fclose(fidout) ;
%% Now let's write 5 additional lines
for iLine=1:5
% simulate a different matrix [A]
A = A + nElem ; % A will continue counting
% permission 'a' => Open or create new file for writing. Append data to the end of the file.
fidout = fopen('myfileout.txt', 'a') ;
fprintf( fidout , writeFormat , A(:) ) ;
fclose(fidout) ;
end
Which should give you the file myfileout.txt, containing:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36

Related

Read a .txt File into a MATLAB matrix

I have a .out file (.txt) in the form:
This is a text file
This file was created by Andrew on 4/5/14
Certificate Result Test #12
Time A B C D
50 4 3 8 9
55 4 8 7 4
60 8 4 1 4
65 7 1 5 1
70 4 2 2 2
How do I read the numbers in the table into a matrix, called M, in MATLAB whilst ignoring all the text at the start?
I have tried using fscan and M = dlmread(filename) but I recieve errors saying Mismatch between file and format string due to the lines of text at the start.
Thanks in advance
Use textscan with the 'HeaderLines' option:
fid = fopen('my_file.out'); % or whatever your file is called
M = textscan(fid,'%d %d %d %d %d','HeaderLines',7); % using int32 data types, change as required
fclose(fid)
Note that M is a cell array
textscan is a powerful tool, with good low level functions. There is also the more convenient 'importdata' which works for many files of this kind:
m = importdata('my.txt', ' ', 6)
m =
data: [5x5 double]
textdata: {6x5 cell}
colheaders: {'Time' 'A' 'B' 'C' 'D'}
As you can see, it not only returns the data in m.data, but you also get the column headers for free.

Using Matlab to make modification to a text file

Essentially I am writing a Matlab file to change the 2nd, 3rd and 4th numbers in the line below "STR" and above "CON" in the text file (which is given below and is called '0.dat'). Currently, my Matlab code makes no changes to the text file.
Text File
pri
3
len 0.03
vic 5 5
MAT
1 147E9 0.3 0 4.9E9 8.5E9
LAY
1 0.000125 1 45
2 0.000125 1 0
3 0.000125 1 -45
4 0.000125 1 90
5 0.000125 1 45
WAL
1 1 2 3 4 5
PLATE
1 0.005 1 1
STR
1 32217.442335442 3010.34241024889 2689.48842888812
CON
1 2 1 2 3 1 3 4 1 4 5 1 5 6 1 6 7 1
ATT
1 901 7 901
LON
34
POI
123456
1 7
X 0.015
123456
2 6
X 0.00381966011250105 0.026180339887499
123456
3 5
X 0.000857864376269049 0.0291421356237309
123456
4
X 0
PLO
2 3
CRO
0
RES
INMOD=1
END
Matlab code:
impafp = importdata('0.dat','\t');
afp = impafp.textdata;
fileID = fopen('0.dat','r+');
for i = 1:length(afp)
if (strncmpi(afp{i},'con',3))
newNx = 100;
newNxy = 50;
newNy = 500;
myformat = '%0.6f %0.9f %0.9f %0.9f\n';
newData = [1 newNx newNxy newNy];
afp{i-1} = fprintf(fileID, myformat, newData);
fclose(fileID);
end
end
From the help for importdata:
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 numeric data. To import ASCII files
with numeric characters anywhere else, including columns of character
data or formatted dates or times, use TEXTSCAN instead of import data.
Indeed, if you print out the value of afp, you'll see that it just contains the first line. You were also not performing any operation that was writing to a file. And you were not closing the file ID if the if state wasn't triggered.
Here is one way to do this with textscan (which is probably faster too):
% Read in data as strings using textscan
fid = fopen('0.dat','r');
afp = textscan(fid,'%s','Delimiter','');
fclose(fid);
isSTR = strncmpi(afp{:},'str',3); % True for all lines starting with STR
isCON = strncmpi(afp{:},'con',3); % True for all lines starting with CON
% Find indices to replace - create logical indices
% True if line before is STR and line after is CON
% Offset isSTR and isCON by 2 elements in opposite directions to align
% Use & to perform vectorized AND
% Pad with FALSE on either side to make output the same length as afp{1}{:}
datIDX = [false;(isSTR(1:end-2)&isCON(3:end));false];
% Overwrite data using sprintf
myformat = '%0.6f %0.9f %0.9f %0.9f';
newNx = 100;
newNxy = 50;
newNy = 500;
newData = [1 newNx newNxy newNy];
afp{1}{datIDX} = sprintf(myformat, newData); % Set only elements that pass test
% Overwrite old file using fprintf (or change filename to new one)
fid = fopen('0.dat','w');
fprintf(fid,'%s\r\n',afp{1}{1:end-1});
fprintf(fid,'%s',afp{1}{end}); % Avoid blank line at end
fclose(fid);
If you're unfamiliar with logical indexing, you might read this blog post and this.
I would recommend just reading the entire file in, finding which lines contain your "keywords", modifying specific lines, and then writing it back out to a file, which can have the same name or a different one.
file = fileread('file.dat');
parts = regexp(file,'\n','split');
startIndex = find(~cellfun('isempty',regexp(parts,'STR')));
endIndex = find(~cellfun('isempty',regexp(parts,'CON')));
ind2Change = startIndex+1:endIndex-1;
tempCell{1} = sprintf('%0.6f %0.9f %0.9f %0.9f',[1,100,50,500]);
parts(ind2Change) = deal(tempCell);
out = sprintf('%s\n',parts{:});
out = out(1:end-1);
fh = fopen('file2.dat','w');
fwrite(fh,out);
fclose(fh);

Reading text file to matrix in Matlab, with unknown line length

I have a text file, that is formatted somewhat like this:
1 2 3 4 5 6
7 8 9
0 11 2 32 45 6 6
1 2
I want to read each row and plot a line for each row.The x axes is [1:row.length],the y axes is each row.
fid = fopen('dat.txt');
line = fgetl(fid);
% if you want everything on the same axis, set it up here
axis([0,20,-10,10])
hold all
while ischar(line)
yy = str2num(line);
xx = 1:length(yy);
plot(xx,yy)
line = fgetl(fid);
end
hold off
fclose(fid);
Note that feof() is not so good with fgetl(), see here.
The simplest way to do it is to test for specific characters. Check for the new line character to determine if you're at the end of the current row and the end of file function to see if you're at the end of the file.
Take a look at: http://www.mathworks.com/help/matlab/ref/feof.html

How to read matrix from text file in matlab?

I have a text file in the same folder as my matlab code called matlab.in, its contents are
training_set = [1 2 3; 4 5 6]
How do I read this matrix into a variable called training_set?
Your text file contains an executable Matlab statement. You could, probably even should, rename it to something like training_set.m (the .m suffix is important) and simply 'read' it from the command line by executing it. On my machine the 'command'
>> training_set
generates the response
training_set =
1 2 3
4 5 6
and, hey presto, the variable training_set is now safely ensconced in your workspace.
Now congratulate yourself for having written your first (?) Matlab script, reward yourself with a visit to the documentation to review this important topic.
First, open it using fopen(...):
fid = fopen('matlab.in');
Second, read the line from the file and close the file again, since you don't need it anymore:
content = fgetl(fid);
fclose(fid);
Third, evaluate the string read from the file:
eval(content);
If you wanted to suppress the output, you might either want to add a semicolon at the end of the text file or instead use:
eval(strcat(content,';'));
file1.txt: 1 2 3 4 5 6 7 8
10 20 30 40 50 60 70 80
[fileID,errmsg] = fopen('file1.txt')
val= textscan(fileID, '%u8')
z = transpose(cell2mat(val))
vec = transpose(reshape(z, [8 2]))
...
Gives you
vec =
2×8 uint8 matrix
1 2 3 4 5 6 7 8
10 20 30 40 50 60 70 80

Read 'm-to-n' row numbers from a txt file (MATLAB)

I'm trying to read data from a .txt file. The sample data is given below. I need an algorithm to read just M-N row numbers. While I can use while/for loops, I'm afraid that it might become very slow. Thanks!
a=[ 1 6 11 16 ;
2 7 12 17 ;
3 8 13 18 ;
4 9 14 19 ;
5 10 15 20] ; % data is in Test.txt -->
% fid = fopen('Test.txt');
% a=a.'; fprintf(fid, '%.3f\t%.3f\t%.3f\t%.3f\r\n', a(:)) ;
fid = fopen('Test.txt') ;
AnsMat = fscanf(fid, '%f %f %f %f')
AnsMat = [2 7 12 17 ; 3 8 13 18] ; % Read row-numbers 2 to 4 this time
You could try textscan which allows a HeaderLines parameter telling matlab how many lines to skip.
For example to read lines n (=2) to m(=4), you could do:
fid = fopen('Test.txt');
C = textscan(fid,'%f %f %f %f\n',m-n+1,'HeaderLines',n-1);
fclose(fid);
This does return the data as a cell array though so you have to convert it:
AnsMat = cell2mat(C);
If your data were in csv format instead of text format, you could use the command:
text=csvread('yourfile.csv',1,1,[1 1 m n])
Obviously, if your data is only available in text format, it would be just as much work to manually convert it as it would be to use the textscan option, but if your text file is being generated elsewhere where you would have control over the output format, this may streamline the process.