Reading rows of data till its end - matlab

I am trying to read the data in column2 until the row ends. I don't know the number of rows of data, but it is finite ( < 100). The columns are space separated:
header line 1
header line 2
header line 3
column1 column2
1 2
3 5
5 7
7 9
. .
. .
. .
header line 4
header line 5
I tried the following code. It works if there are no further header lines:
mydata = dlmread('data.txt', '', 4, 1)
How does it work with further header lines after the data rows as shown above ends?

An easier solution is to use textscan to read your file. You can specify the number of header lines as an extra argument to the function call. The additional lines at the end of your file are ignored by the function when you specify the correct conversion specifier.
fileID = fopen('data.txt');
mydata = textscan(fileID,'%d%d','HeaderLines',4);
fclose(fileID);
mydata{2} contains data from column 2.

An easy approach is reading the file in string format, removing the lines, and writing to the new file.
% Read the file
fid = fopen(filePath,'r');
str = textscan(fid,'%s','Delimiter','\n');
fclose(fid);
% Extract number lines
str2 = str{1}(5:end-2);
% Save as a text file
fid2 = fopen('new.txt','w');
fprintf(fid2,'%s\n', str2{:});
fclose(fid2);
mydata = dlmread('new.txt','',0,1);

Related

string concatenation from a .txt file matlab

I am trying to concatenate three lines (I want to leave the lines as is; 3 rows) from Shakespeare.txt file that shows:
To be,
or not to be:
that is the question.
My code right now is
fid = fopen('Shakespeare.txt')
while ~feof(fid)
a = fgets(fid);
b = fgets(fid);
c = fgets(fid);
end
fprintf('%s', strcat(a, b, c))
I'm supposed to use strcat and again, I want concatenated and leave them as three rows.
One method of keeping the rows separate is by storing the lines of the text file in a string array. Here a 1 by 3 string array is used. It may also be a good idea to use fgetl() which grabs each line of the text file at a time. Concantenating the outputs of fgetl() as strings may also be another option to ensure the they do not get stored as character (char) arrays. Also using the \n indicates to line break when printing the strings within the array String_Array.
fid = fopen('Shakespeare.txt');
while ~feof(fid)
String_Array(1) = string(fgetl(fid));
String_Array(2) = string(fgetl(fid));
String_Array(3) = string(fgetl(fid));
end
fprintf('%s\n', String_Array);
Ran using MATLAB R2019b

Read first line of CSV file that contains text in cells

I have a deco.csv file and I only want to extract B1 to K1 (20 columns of the first rows), i.e. Deco_0001 to Deco_0020.
I first make a pre-allocation:
names = string(20,1);
and what I want is when calling S(1), it gives Deco_0001; when calling S(20), it gives Deco_0020.
I have read through textscan but I do not know how to specify the range is first row and running from column 2 to column 21 of the csv file.
Also, I want save the names individually but what I have tried just save the first line in only one cell:
fid=fopen('deco.csv');
C=textscan(fid, '%s',1);
fclose(fid);
Thanks!
It's not very elegant, but this should work for you:
fid=fopen('deco.csv');
C=textscan(fid, '%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s',1,'Delimiter',',');
fclose(fid);
S = cell(20,1);
for ii = 1:20
S{ii} = C{ii+1};
end

How do I read comma separated values from a .txt file in MATLAB using textscan()?

I have a .txt file with rows consisting of three elements, a word and two numbers, separated by commas.
For example:
a,142,5
aa,3,0
abb,5,0
ability,3,0
about,2,0
I want to read the file and put the words in one variable, the first numbers in another, and the second numbers in another but I am having trouble with textscan.
This is what I have so far:
File = [LOCAL_DIR 'filetoread.txt'];
FID_File = fopen(File,'r');
[words,var1,var2] = textscan(File,'%s %f %f','Delimiter',',');
fclose(FID_File);
I can't seem to figure out how to use a delimiter with textscan.
horchler is indeed correct. You first need to open up the file with fopen which provides a file ID / pointer to the actual file. You'd then use this with textscan. Also, you really only need one output variable because each "column" will be placed as a separate column in a cell array once you use textscan. You also need to specify the delimiter to be the , character because that's what is being used to separate between columns. This is done by using the Delimiter option in textscan and you specify the , character as the delimiter character. You'd then close the file after you're done using fclose.
As such, you just do this:
File = [LOCAL_DIR 'filetoread.txt'];
f = fopen(File, 'r');
C = textscan(f, '%s%f%f', 'Delimiter', ',');
fclose(f);
Take note that the formatting string has no spaces because the delimiter flag will take care of that work. Don't add any spaces. C will contain a cell array of columns. Now if you want to split up the columns into separate variables, just access the right cells:
names = C{1};
num1 = C{2};
num2 = C{3};
These are what the variables look like now by putting the text you provided in your post to a file called filetoread.txt:
>> names
names =
'a'
'aa'
'abb'
'ability'
'about'
>> num1
num1 =
142
3
5
3
2
>> num2
num2 =
5
0
0
0
0
Take note that names is a cell array of names, so accessing the right name is done by simply doing n = names{ii}; where ii is the name you want to access. You'd access the values in the other two variables using the normal indexing notation (i.e. n = num1(ii); or n = num2(ii);).

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!

MatLab - How to read a text file separated by ';', with different number of columns [duplicate]

This question already has answers here:
Fastest way to import CSV files in MATLAB
(4 answers)
Closed 9 years ago.
I'm trying to read a .txt file that is ';' delimited with date in the 'header' and diferent columns after the 'header'. I'm using quotes to HEADER because it's more like a parameter line.
So, the .txt is like (the other lines have the same number of columns):
15/07/2013;66;157
DDD;3;1;0;1;1;1;-0.565
DDD;8;2;0;2;1;1;-0.345
DDD;9;3;2;3;1;2;-0.643
DDD;8;1;3;5;1;3;-0.025
DDD;8;1;0;9;1;4;-0.411
DDD;15;1;5;4;1;5;-0.09
DDD;12;1;0;5;1;6;-0.445
DDD;13;1;0;7;1;7;-0.064
I want to read and create a matrix, that contains each data in one cell, like:
matrix =
[15/07/2013 66 157
DDD 3 1 0 1 1 1 -0,565
DDD 8 2 0 2 1 1 -0,345
DDD 9 3 2 3 1 2 -0,643
...]
I've tried textscan, cvsread, textread and nothing works!
Thanks in advance!
Edit: Actually, I found a WAY FASTER code to do this!
From my past experience, MATLAB does not like strings and numbers to be in the same matrix, so you would be forced to use a cell.
You can do this relatively easily with some simple paring.
fid = fopen('temp.txt','r'); %# open file for reading
count = 1;
content = {};
while ~feof(fid)
line = strtrim(fgets(fid)); %# read line by line
parts = regexp(line,';','split');
for i = 1:numel(parts)
temp = regexp(parts{i},'-?[0-9]*\.?[0-9]*(i|j)?','match');
if numel(temp) >= 1 && strcmpi(temp{1},parts{i})
parts{i} = str2double(parts{i}) ;
end
end
content{count} = parts;
count = count + 1;
end
fclose(fid);
numRows = size(content,2)-1;
whole = cell(numRows,8);
for i = 1:numRows
for j = 1:8
whole{i,j} = content{i+1}{j};
end
end
content = {content{1},whole};
UPDATE
I added some stuff to put everything into a single cell array, all of the data outside of the header. I do not know if you wand the header to also be in that 8 column array, but if you do here is some code to do that
numRows = size(content,2);
whole = cell(numRows,8);
for i = 1:numRows
for j = 1:min([size(content{i},2),8])
whole{i,j} = content{i}{j};
end
end
whole