why textscan does not read all rows matlab - matlab

I have a text file which have 5 columns. Here is sample data:
book 1 3 5 7
paper 3 9 0 2
pen 3 1 2 0
pencil 9 0 3 9
The first column contains character and the other columns are just number. The file contains several rows. I am trying to read that .txt as follows;
fileID = fopen('filename.txt');
C = textscan(fileID,'%s %n %n %n %n');
fclose(fileID);
celldisp(C)
It read the column correctly. However, it reads only the first row, and not all. Why it is happening that way? How to do if I want to read all rows and all columns. Thanks

I assume you want to create a cell array in which every cell contains a single element from your text file.
The code you provided so far is correct:
fileID = fopen('filename.txt');
C = textscan(fileID,'%s %n %n %n %n');
fclose(fileID);
However now each cell in C contains an entire column from your txt file:
where C{1,1} contains the first column, that are four strings (book, paper, pen, pencil).
Now it is time un "unwrap" such cells using this piece of code:
for i=1:size(C,2)
if(iscell(C{:,i}))
A(:,i)=reshape(C{:,i},length(C{:,i}),1);
else
A(:,i)=num2cell(reshape(C{:,i},length(C{:,i}),1));
end
end
that basically says "if the cell contains a cell (see C{1,1}) just unwrap its content in length(C{:,i}) different cells. As instead if the cell contains an array, assign each element of this array to a different cell.".
Now the cell array A has the form
and I hope this is what you're looking for.

Related

Combine elements of a cell into a matrix

I have a cell (called AA ) that contains 1 row * 36 columns (as shown in the attached image)
As we could see that each column in that cell is a matrix ( inside each column there are 1*3 data points )
I need to have an array that has 36 Rows * 3 columns in MATLAB
For example,
the first column in the Cell will be converted into 1 Row and three columns, the second column in the Cell will be converted in the same way and finally put them all of them together in order to generate an array that contains 36 Rows and 3 Columns
as shown in this example
-1.48247427405830e-15 0.185513882360673 -0.185513882360676
-9.59200039657764e-16 0.211729497802758 -0.211729497802760
3.69087930153418e-16 0.224791092084074 -0.224791092084073
You can just use cat to concatenate the rows and use {:} indexing to create a comma separated list
output = cat(1, AA{:})
In addition to the answer of the gentleman Suever these are 2 methods as well that can be used to solve the same question
output =cell2mat(AA(:))
or, more simply,
output = vertcat(AA{:})

Matlab write cell array of numbers into file

I have a cell array like this:
cellarr{1}=[1 2 3];
cellarr{2}=[1 2 3 4 5 6];
...
Each cell is a vector of numbers with different length. I want to write this cell array into a text file so that i can read it later. The text file should look like this:
1 2 3
1 2 3 4 5 6
If I use dlmwrite('file.txt',cellarr,'\t') it puts all cells into one line. How do I put a new line character after writing a cell to the text file?
P/S: I could use fprintf with two for loops to get what I want. But is there a faster way to do that?
I was wondering why do you need two for loops?
fid = fopen('file.txt', 'wt');
for i = 1 : length(cellarr)
fprintf(fid, '%d\t', cellarr{i});
fprintf(fid,'\n');
end
fclose(fid)

Writing to a text file in Matlab

I've come across numerous ways to write matlab data to a .txt file but I am unsure which way would be best suited for my needs - I have two sets of data labelled 'x' and 'y' within which data simply runs down 1 column (A1....An) and I need a tab delimited .txt file made with the format:
Name X X Y
Test 2 2 5.5
Test 3 3 6.5
Test 4 4 7.5
etc...
Whereby I can have 2 identical columns of the X data, followed by the Y data. I also need to be able to input something for the 'Name' column which will copy itself down until the data in X/Y stops. I don't need any column headers in it i.e. 'X' 'Y' or 'Name' just the data itself.
What would be the best way to go about this?
Run this code example and you can check that it does what you want:
% Example data:
x = [1:5];
y = rand(1,5);
fileID = fopen('yourfile.txt','w');
for i = 1:length(x)
fprintf(fileID,'%s\t%d\t%d\t%f\n', 'Test', x(i),x(i),y(i));
end
fclose(fileID);
Opening the text file you will see something like:
Test 1 1 0.655741
Test 2 2 0.035712
Test 3 3 0.849129
Test 4 4 0.933993
Test 5 5 0.678735
If you want the value for string 'Test' to change in each row, simply pass in an array with those string values, similar to how the x and y variables are passed to the fprintf() statement.
One way is to first put everything into a single cell:
Name = repmat({'Test'}, [1 DataSize]); % A Cell containing n 'Test' string
C = [Name num2cell(X') num2cell(X') num2cell(Y')]; % Concatenating cells
Then use fprintf to write the cell into a file:
fid = fopen('data.txt', 'wt');
fprintf(fid, '%s\t%d\t%d\t%d\n', C{:});
fclose(fid);
Hope it helps.

MATLAB Creating a .txt file containing numbers and strings from a cell

Dear stackoverflowers,
I'd like to create a .txt file using matlab.
The content should be separated with tabs.
It should have 3 columns, and the 3rd column should be filled with strings from a cell array.
Let's say
A=[2; 3; 3;];
B=2*A;
C=cell(3,1);
C{1,1}='string1'; C{2,1}='string2'; C{3,1}='string3';
In the end, it should look like this:
2 4 string1
3 6 string2
3 6 string3
I already found out, how to put the 2 matrices in a text file:
dlmwrite('filename.txt', [A B], 'delimiter', '\t')
But how to append the content of the cell?
It would be best, to have only the strings in the file, not the single quotes.
I neither found a solution to this elsewhere, nor did I ask this somewhere else.
I apprechiate all kinds of suggestions.
Try the following:
% Open a file for writing (if you want to append to file use 'a' instead of 'w')
fid = fopen(file,'w');
for i = 1:size(A,1)
fprintf(fid,'%d %d %s\n',A(i),B(i),C{i})
end
fclose(fid)
Hope this helps
the documentation on dlmwrite states:
Remarks
The resulting file is readable by spreadsheet programs.
The dlmwrite function does not accept cell arrays for the input matrix
M. To export a cell array that contains only numeric data, use
cell2mat to convert the cell array to a numeric matrix before calling csvwrite.
To export cell arrays with mixed alphabetic and numeric
data, where each cell contains a single element, you can create an
Excel spreadsheet (if your system has Excel installed) using xlswrite.
For all other cases, you must use low-level export functions to write
your data.
So either you write it as an Excel spreadsheet, or use have to write your own conversion function.
For example
A=[2; 3; 3;];
B=2*A;
C=cell(3,1);
C{1,1}='string1'; C{2,1}='string2'; C{3,1}='string3';
% First solution
f = fopen('filename.txt', 'w');
for n = 1:3
fprintf(f, '%d\t%d\t%s\n', A(n), B(n), C{n});
end
fclose(f);
% Another solution
% create the table as a single cell array with only strings
C2 = [arrayfun(#num2str, [A, B], 'UniformOutput', false) C]'; % <- note the transpose
f = fopen('filename.txt', 'w');
fprintf(f, '%s\t%s\t%s\n', C2{:}); % <- every three entries are written as a line
fclose(f);

Reading text values into matlab variables from ASCII files

Consider the following file
var1 var2 variable3
1 2 3
11 22 33
I would like to load the numbers into a matrix, and the column titles into a variable that would be equivalent to:
variable_names = char('var1', 'var2', 'variable3');
I don't mind to split the names and the numbers in two files, however preparing matlab code files and eval'ing them is not an option.
Note that there can be an arbitrary number of variables (columns)
I suggest importdata for operations like this:
d = importdata('filename.txt');
The return is a struct with the numerical fields in a member called 'data', and the column headers in a field called 'colheaders'.
Another useful interface for importing manipulating data like these is the 'dataset' class available in the Statistics Toolbox.
If the header is on the first row then
A = dlmread(filename,delimString,2,1);
will read the numeric data into the Matrix A.
You can then use
fid = fopen(filename)
headerString = fscanf(fid,'%s/n') % reads header data into a string
fclose(fid)
You can then use strtok to split the headerString into a cell array. Is one approach I can think of deal with an unknown number of columns
Edit
fixed fscanf function call
Just use textscan with different format specifiers.
fid = fopen(filename,'r');
heading = textscan(fid,'%s %s %s',1);
fgetl(fid); %advance the file pointer one line
data = textscan(fid,'%n %n %n');%read the rest of the data
fclose(fid);
In this case 'heading' will be a cell array containing cells with each column heading inside, so you will have to change them into cell array of strings or whatever it is that you want. 'data' will be a cell array containing a numeric array for each column that you read, so you will have to cat them together to make one matrix.