Write a cell array in text file using Matlab - matlab

I have a cell array with the size of 1*15.
whos C
Name Size Bytes Class Attributes
C 1x15 222520 cell
In each cell, there are 1170 elements. The 15 cells are mixture of strings and numbers. I want to save all these elements to a text file with coma as delimiter.
I tried to use the function dlmcell, dlmcell('file_out.txt.,C,'delimiter',','), it can only write the first value of each cell to the text file. And the cell contains string cannot be write to the text file.
Can anyone help? Thanks!

I just found in http://cn.mathworks.com/help/matlab/import_export/write-to-delimited-data-files.html
write cell data using fprintf.
May help!
[nrows,ncols] = size(C);
for row = 1:nrows
fprintf(fileID,formatSpec,C{row,:});
end

Related

Writing the output of variable length cells into a single column cell array in MATLAB

I am trying to write the output from a variable length cell array to a single column cell array.
Eg:
I have
A a;b
B c
C b;c
D a;b;d
E e;g;h
F a;b
as the input file. I want to read all the entries in the second column into separate cells in a row and store the output as the following:
a
b
c
b
c
a
b
d.... and so on.
I tried
for m=1:size(txt)
c(:,m)=strsplit(txt{m},';');
end
However, I am unable to write the output into a column and getting the following error:
Assignment has more non-singleton rhs dimensions than non-singleton subscripts
I understand that the dimensions of c should be more than that of size(txt) but I am not sure how to enter write the output from c into the first empty cell present in the column.
This is because you have declared c to be a matrix but you want it to be a single column. In addition, strsplit creates a cell array of results here each split string is placed in an element in the cell array. Also, this cell array is a row-wise cell array, meaning that you will get a cell array of dimensions 1 x N where N is the total number of strings resulting from the call the strsplit.
As such, what I would recommend you do is create a master cell array to store all of the strings as you iterate through each row, then concatenate and create one final cell array at the end.
Assuming the code you wrote up until this point is correct, do something like this:
c = cell(numel(txt), 1);
for m = 1 : numel(txt)
c{m} = strsplit(txt{m}, ';');
end
c = horzcat(c{:});
The first line creates a master cell array to store our string split characters per line of the text file. Next, for each line of the file, we split the string with the semicolon character as the delimiter and we place these split results into the right cell in the master array. Once this is finished, we use horzcat to place all of the characters into a single row of cells in the end. This creates a row of cell array elements though. Using horzcat is required as we are concatenating many row-wise cell arrays together into a single row. Trying to do this vertically will give you an error. Simply transpose the result if you want a column:
c = horzcat(c{:}).';

why textscan does not read all rows 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.

Concatenate and pull out data from cell array

I have a cell array called d_O3 of size 3x15.
Here's what the first row looks like:
10x29 cell
31x29 cell
40x29 cell
...
I want to turn column one inside each cell into a column array and vertically concatenate them all together.
Here's what I've done so far:
years = 1999:2013; % The 15 columns
m = 1; % Row 1. I'd like to be able to run a loop for the other rows to do the same thing, but I haven't figured out how.
for y = 1:numel(years)
data{y,1} = d_O3{m.y}(:,1);
end
This creates a 15x1 cell that looks like this inside:
31x1 cell
40x1 cell
42x1 cell
...
Inside each cell (i.e. inside 31x1), there's a column array of strings. But I want it to all concatenate together so it looks like:
06-029-0001-88101
06-073-0010-88101
...
In other words, I want to make vertically concatenate all the cells above.
I can do it by doing the following:
vertcat(data{1,1},data{2,1},...)
But that would mean typing out data{i,1} 15 times. What's an easier way?
vertcat(data{1:15,1})
or
vertcat(data{:,1})
It creates a comma separated list which is passed to vertcat.

Matlab: cell to matrix row

I am trying to convert a text file (comma seperated values) to a matrix in MATLAB. I have been able to fetch the individual lines into cell array but I can't convert those values to a matrix form. The 7X1 cell obtained by reading the line of the file is a row major and has the following values
line =
'123'
''
'"Foo"'
[1X27 char]
'1.01'
'2.02'
'0'
So, the file is basically a collection of similar lines. Any suggestion as to how can I convert these lines to a matrix form ? Any help would be appreciated.
You can use the cell2mat function to create a matrix from your cell (see MATLAB help page for details). As your cell is a column vector and you want a row vector, you will have to transpose the cell first.
row = cell2mat(line.');
If you want to add a space between all elements, here's a way to do this:
% Remove all empty fields
line = line(~cellfun(#isempty,line));
% Add a space after each element
line = strcat(line,{' '});
% Now call cell2mat
row = cell2mat(line.');
% and remove space at end
row = strtrim(row);
You can use regexpi to find quotation marks and remove them.
row = row(regexpi(row,'"')) = '';

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.