How to read matrix from text file in matlab? - 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

Related

How to save several times without overwriting the file

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

Matlab random sampling

I am trying to exercise myself in Matlab. I am trying to select randomly two lines from a file named data.dat.
My data.dat file looks like this:
12 4 6.1 7
14 4 8.4 62
7 56.1 75 98
9.7 54 12 35
2 4 8 7.8
To select 2 lines randomly from the data.dat here is how I am proceeding:
close all;
clear all;
%----------------------%
% Choose random lines
%----------------------%
M = load('data.dat');
N=2; %number_of_lines
file_number = 2; %save each two lines in new file: selection_1, selection_2
Now I am saving the two selected lines in new files sequentially.
for k = 1:file_number
i = randi(length(M),N);
B=M(i,:)
filename=['samples_',int2str(k),'_mc.dat']
save (filename, 'B', '-ascii')
clear B;
end
I don't know why but I have more than 2 lines in each new files. Could you please explain me where did I made a mistake.
I think you are making a mistaking when you generate the random numbers, as indicated by GameOfThrows.
i = randi(length(M),N); % gives you a matrix NxN of numbers
i = randi(length(M),[N,1]); % gives you a column of N numbers

MATLAB: How to read data from a text file that have a certain character

I have a txt file, which contains a bunch of random data in two units, Distance (m) and Time (seconds). For example the txt file looks like this:
5 metre
0 sec
10 metre
1 sec
16 metre
2 sec
25 metre
3 sec
I want to be able to store all of the metres values into an array, and the seconds data into another. Basically separating the text file into two arrays based on the metre/sec units.
You could use readtable
I don't know whether this is the 'right' function, but this works :)
Read Data:
A = readtable('Input.txt','Delimiter',' ','ReadVariableNames',false);
Output would be something like this:
A =
Var1 Var2
____ _______
5 'metre'
0 'sec'
10 'metre'
1 'sec'
16 'metre'
2 'sec'
25 'metre'
3 'sec'
%// use 'cellfun' to create a mask of which unit corresponds to 'metre'
mask = cellfun(#(x) strcmp(x,'metre'), A.Var2);
%// save the corresponding data in one variable and rest in another
m = A.Var1(mask);
s = A.Var1(~mask);
Output:
>> m
m =
5
10
16
25
>> s
s =
0
1
2
3
Try this:
% Build a dummy txt data
txt = '';
for i=1:100
txt = sprintf('%s%d metre\n%d sec\n',txt,2*i, i);
end
txt = regexprep(txt,'\n\n','\n')
data = sscanf(txt,'%d metre\n%d sec\n',[2 Inf])';
the regexprep() should take care of accidental double line breaks, while sscanf() parses the data in the right format.

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.

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