Matlab - read specifics of textfile and give specific output - matlab

I have a text file in Matlab that contains comment strings as well as variables and I am trying to figure out the best way to read this file and give an output as different variables that can easily be plugged into equations later on.
The text file looks something like this:
#Comments
2
#Comments
#Comments
1.1 2.55 4.32
1.9 2.76 8.95
1 3.65 9.12
I want an output so that each number is given a variable and the strings with the #s in front are ignored.
ex output:
i=2
a1=1.1
b1=2.55
c1=4.32
a2=1.9
b2=2.76
c2=8.95
a3=1
b3=3.65
c3=9.12
And these variables will be stored for later use. Thanks in advance to anyone who can help.

If you used textscan you can set the CommentStyle to # - this will ignore the lines starting with a #. Looking at your data, you should set your delimiter to a space. As some of your lines seem to be shorter than others you should probably set the EmptyValue parameter - this will replace any empty fields with a flag of your choosing, for example Inf or NaN, or just zero. The command will look something like this:
fid = fopen(filename)
data = textscan(fid, '%f%f%f', 'Delimiter', ',', 'CommentStyle', '#', 'EmptyValue', NaN)
This will put your data into a cell array - I am not sure how you could elegantly assign each value to a completely different variable.

Related

Reading data from .txt file into Matlab

I have been trying in vain for days to do one seemingly simple thing--I want to read data from a .txt file that looks like this:
0.221351321
0.151351321
0.235165165
8.2254546 E-7
into Matlab. I've been able to load the data in the .txt file as a column vector using the fscanf command, like so:
U=fscanf(FileID, '%e')
provided that I go through the file first and remove the space before the 'E' wherever scientific notation occurs in the data set.
Since I have to generate a large number of such sets, it would be impractical to have to do a search-and-replace for every .txt file.
Is there a way for matlab to read the data as it appears, as in the above example (with the space preceding 'E'), and put it into a column vector?
For anyone who knows PARI-GP, an alternate fix would be to have the output devoid of spaces in the first place--but so far I haven't found a way to erase the space before 'E' in scientific notation, and I can't predict if a number in scientific notation will appear or not in the data set.
Thank you!
Thank you all for your help, I have found a solution. There is a way to eliminate the space from PARI-GP, so that the output .txt file has no spaces to begin with. I had the output set to "prettymatrix". One needs to enter the following:
? \o{0}
to change the output to "Raw," which eliminates the space before the "E" in scientific notation.
Thanks again for your help.
A simple way, may not be the best, is to read line by line, remove the space and convert back to floating point number.
For example,
x = []
tline = fgetl(FileID);
while ischar(tline)
x = [x str2num(tline(find(~isspace(tline))))]
tline = fgetl(FileID);
end
One liner:
data = str2double(strsplit(strrep(fileread('filename.txt'),' ',''), '\n'));
strrep removes all the spaces, strsplit takes each line as a separate string, and str2double coverts the strings to numbers.

Read hex from file matlab

What I have
A txt file like:
D091B
E7E1F
20823
...
What I need
To read them and store them like char, just as they are in the file: N (don't knot how many) lines, with its 5 characters (5 columns) at each one.
What have I tried
fichero = fopen('PS.txt','r');
sizeDatos = [[] 5]; % Several Options, read below
resultados=fscanf(fichero, '%s', sizeDatos); % Here too
fclose(fichero);
I've tried with the snippet above, to read my txt file. However, I didn't manage to get it. Most I've obtained is, using:
sizeDatos = [1 Inf];
So I got all my hex characters into an array, with no spaces.
As you can see, I've tried several optios changing fscanf size parameter, as well as trying to say into the format chain that it should recognize new lines by using \n for example. None of them have worked for me.
Any idea about how can I get it? I've readed fscanf page from documentation, but it didn't inspire me to make anything different.
One possible solution is using textscan and convert it to a cell array.
fileId = fopen('PS.txt');
C = textscan(fileId, '%s');
Now to show the content of cell you can use
celldisp(C)
Or you can convert it to other types.
Don't forget to close your file after using it.

Outputting a word file using Matlab

I want to write a function that takes number n as input, then outputs a tab separated word document that looks like 5 rows of:
1 2 3...n n n-1 n-2 ..1
Let me tell you what I have tried already: It is easy to create a vector like this with the integers I want, but if I save a file in an ascii format, in the output the integers come out in a format like " 1.0000000e+00".
Now I googled to find that the output can be formatted using %d and fprintf, but given the row length is part of the input, what would be the most efficient way to achieve it?
maybe something like this:
Nrow = 5;
N = 10;
dlmwrite('my_filename.txt', repmat([1:N, N:-1:1], Nrow, 1), 'delimiter', '\t', 'precision', '%d');
If you mean a normal *.txt kind of file, I would normally use a for loop with fprintf(fileid,'%d things to print',5), with the appropriate fopen(.) statement. You'd be surprised what a good job fopen with 'w' and 'a' does. Try it and let us know!
In response to rayryeng: You are right! Here is a sample of code for writing a matrix to file using fprintf, without a for-loop.
A=rand(5);
fid=fopen('Rand_mat.txt','w');
fprintf(fid,'%0.4f %0.4f %0.4f %0.4f %0.4f\n',A');
fclose (fid);
where A is transposed because MATLAB reads the columns of the matrix first.
Thanks!

Create a simple table in Matlab

I've been fighting with fprintf for an hour now, should be easy but it's not apparently.
Have a vector with descriptive statistics called datasave, contains 9 numbers like average, standard dev, kurtosis etc.
And I have a vector datalabels with the lablels 'Average' , 'St.dev', 'Kurt' etc.
Open a file with fileopen
print the labels
new line
print the values ( exactly under the labels!)
close the file
This is what I've tried so far:
fileID = fopen('descstat2.txt','w');
fprintf(fileID,'MediaTonnes MinTonnes MaxTonnes Sigma Skew Kurt SigmadTonnes SkewdTonnes KurtdTonnes\r\n');
format short;
fprintf(fileID, '%g\t%g\t%g\n', datasave.');
Help?
I have at least 50 different combinations so I can't really give you my output...
Maybe try this:
fileID = fopen('descstat2.txt','w');
fprintf(fileID,'%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n', datalabels);
fprintf(fileID, '%g\t%g\t%g\t%g\t%g\t%g\t%g\t%g\t%g\r\n', datasave);
fclose
To use XLSWRITE you need to create a cell array:
out = [datalabels(:)'; num2cell(datasave)];
xlswrite('descstat2', out)
If the file you are saving to is exist as a text file, xlswrite will save it as a text as well.
It probably will be slower that fprintf (due to COM interface) but you don't have to deal with formatting the output. Just need to convert everything to cells.
Another option is to use TBLWRITE from Statistical Toolbox. You can just do:
tblwrite(datasave, datalabels, [], filename, '\t')
It will also put row numbers or labels specified as 3rd argument. Might be useful for some data.

How do you create a matrix from a text file in MATLAB?

I have a text file which has 4 columns, each column having 65536 data points. Every element in the row is separated by a comma. For example:
X,Y,Z,AU
4010.0,3210.0,-440.0,0.0
4010.0,3210.0,-420.0,0.0
etc.
So, I have 65536 rows, each row having 4 data values as shown above. I want to convert it into a matrix. I tried importing data from the text file to an excel file, because that way its easy to create a matrix, but I lost more than half the data.
If all the entries in your file are numeric, you can simply use a = load('file.txt'). It should create a 65536x4 matrix a. It is even easier than csvread
Have you ever tried using 'importdata'?
The parameters you need only file name and delimiter.
>> tmp_data = importdata('your_file.txt',',')
tmp_data =
data: [2x4 double]
textdata: {'X' 'Y' 'Z' 'AU'}
colheaders: {'X' 'Y' 'Z' 'AU'}
>> tmp_data.data
ans =
4010 3210 -440 0
4010 3210 -420 0
>> tmp_data.textdata
ans =
'X' 'Y' 'Z' 'AU'
Instead of messing with Excel, you should be able to read the text file directly into MATLAB (using the functions FOPEN, FGETL, FSCANF, and FCLOSE):
fid = fopen('file.dat','rt'); %# Open the data file
headerChars = fgetl(fid); %# Read the first line of characters
data = fscanf(fid,'%f,%f,%f,%f',[4 inf]).'; %'# Read the data into a
%# 65536-by-4 matrix
fclose(fid); %# Close the data file
The easiest way to do it would be to use MATLAB's csvread function.
There is also this tool which reads CSV files.
You could do it yourself without too much difficulty either: Just loop over each line in the file and split it on commas and put it in your array.
Suggest you familiarize yourself with dlmread and textscan.
dlmread is like csvread but because it can handle any delimiter (tab, space, etc), I tend to use it rather than csvread.
textscan is the real workhorse: lots of options, + it works on open files and is a little more robust to handling "bad" input (e.g. non-numeric data in the file). It can be used like fscanf in gnovice's suggestion, but I think it is faster (don't quote me on that though).