How do I read comma separated doubles from text file into MATLAB? - matlab

I have a text file called Output.txt that looks like this:
0.000000,0.550147,0.884956
1.000000,0.532486,0.847458
2.000000,0.501333,0.800000
3.000000,0.466418,0.746269
4.000000,0.409492,0.662252
5.000000,0.327257,0.520833
6.000000,0.267376,0.425532
7.000000,0.188427,0.296736
8.000000,0.115824,0.180505
9.000000,0.062768,0.099108
I need to read in the three values separated by commas into MATLAB as 3 different vectors. They can be called anything but C1, C2, and C3 could work.
C1 would contain [0.000000,1.000000,2.000000, ...], C2 would contain [0.550147,0.532486,...] and C3 would contain the values in the third column [0.884956,0.847458,...].
I tried using the following but I'm having problems getting it to work correctly:
File = 'Output.txt';
f = fopen(File, 'r');
C = textscan(f, '%f%f%f', 'Delimiter', ',');
fclose(f);
This gives me a 1x3 Cell array C but each of the cells in C are 1x100 and do not contain the correct numbers.

You have a Comma Separated Value file, so you can simply use csvread to read in your matrix:
C = csvread('Output.txt');
where C now is a matrix containing all your values, which you can of course index through columns and rows. I'd recommend against creating the column vectors rather use C(:,1) for the first column etc.

Related

Converting csv of strings into a matrix

I just started using Octave (No money for Matlab :/) and I'm also new to Stack Overflow, so please pardon any error I make with conventions.
Problem: I have a csv of strings like so:
Bob Marley,Kobe Bryant,Michael Jackson,Kevin Hart
I would like to make this into a 1 column matrix (I need it in a matrix so that I can combine it with data that are in other matrices).
My approach: I have tried doing textread, but this gives me a cell array. I tried converting the resulting cell array to a matrix by using cell2mat, but I suspect that I cannot do this because my strings are of varying lengths.
Let me know if any other information is necessary.
You can use char arrays using:
fid = fopen('strings.csv');
A = textscan(fid, '%s', 'delimiter', ',');
B = char(A{:})
[rows, cols] = size(B)
Output is the following:
B =
Bob Marley
Kobe Bryant
Michael Jackson
Kevin Hart
rows = 4
cols = 15
As you can see, the number of columns of B is the maximum length of all "strings" (Michael Jackson, 15). All other "strings" get whitespaces appended.
Considering you are in the directory where you have a file "strings.csv" with the content you mentioned in the question, your code whould look like this:
fid=fopen('strings.csv');
A=textscan(fid,'%s','delimiter',',');
A=A{1};
A=cellfun(#(x) string(x),A,'uni',0);
B=[A{:}];
If your data is that simple, you can do it in a one-liner. Use fileread to slurp all the data in, and then strsplit to separate the elements, and a ' transpose to convert it to a column vector.
x = strsplit(fileread('myfile.txt'), ',')'
If you end up with spaces around the commas in your data, upgrade to regexp.
x = regexp(fileread('myfile.txt'), ' *, *', 'split')

Matlab: how to write cell array of matrices to file

i have a cell of several matrices (all double and with the same dimension)
my_cell =
[172x15 double] [172x15 double] [172x15 double] [172x15 double]
I would to write the matrices on txt file side by side and tabulated, to obtain a .txt file with 172 rows and 60 columns (in this case)
use dlmwrite and cell2mat
mat = cell2mat(my_cell);
delimiter = ' '; % // used to separate two values in a row in the file
filename = 'test.txt';
dlmwrite(filename,mat,delimiter);
>> dlmwrite('file1.txt', [c{:}],'delimiter','\t','precision','%.5f')
or
>> dlmwrite('file2.txt', c(:)','delimiter','\t','precision','%.5f')
You have to choose a precision, otherwise you'll get non-uniform lines because of different numbers of decimal places.
Code
%// output_filepath is the name of your output text file
c1 = horzcat(my_cell{:})
datacell = mat2cell(c1,ones(1,size(c1,1)),ones(1,size(c1,2)))
dlmwrite(output_filepath,datacell,'\t'); %// a TAB delimiter is used

How to save data transposed in a tab-delimited file

Assuming you have an array of 5 lines by n columns as a MATLAB variable.
How do you save to a file each column of the array into a new array as as follows:
column1 becomes line1 and so on.
I need this to be without comas between elements so it should be something along the lines of
dlmwrite('pointcloud.pts', cloud, 'delimiter', '\t');
produces
but I want column one to be saved as line one.
I think you only have to transpose your matrix. Here's an example:
n = 7;
test = rand(5, n);
dlmwrite('pointcloud.pts', test', 'delimiter', '\t');
For me it works fine. -> ' <- is the operator to transpose... Or did I understand you wrong?
EDIT: Look, I think that you are still saving the not transposed matrix. So in your case you are still saving the first 443250 elements of the first row into the first row of your file. By transposing your data with the apostroph ' you transpose the data and can store it correctly. Have a look at my code: you will see one apostrophe (as operator to transpose) after >test<.
You can see that for example if you type:
a = rand(2, 4);
a_transposed = a';

How to import data with row and column headers

I want to import data from a text file with row and column headers, and it in a matrix. For instance, the input file looks as follows:
data c1 c2 c3 c4
r1 1 2 3 4
r2 5 6 7 8
Also, is it possible to access the row and column names with the corresponding data element? And is it possible to modify that based on the result of operations?
Thanks in advance.
I would use textscan with an extra %*s in the format string to gobble up the first header column in each row. The first header row should be used to count the number of columns, in case it is unknown:
fid = fopen('input.txt'); %// Open the input file
%// Read the first header row and calculate the number of columns in the file
C = textscan(fid, '%s', 1, 'Delimiter', '\n', 'MultipleDelimsAsOne', true);
cols = numel(regexp(C{1}{1}, '\s*\w+'));
%// Read the rest of the rows and store the data values in a matrix
C = textscan(fid, ['%*s', repmat('%f', 1, cols - 1)]);
A = [C{:}]; %// Store the data in a matrix
fclose(fid); %// Close the input file
The data is stored in matrix A.
From the documentation on readtable see http://www.mathworks.com/help/matlab/ref/readtable.html
T = readtable(filename, 'ReadVariableNames', true) if the first column has the headers
or
T = readtable(filename, 'ReadRowNames', true) if the first row has the headers
You may also be interested into the 'HeaderLines' name-value pair if you'd like to drop more than just the first line.
You could use importdata, for example, supposing the delimiter is "tab",
rawdata = importdata(filename, '\t');
row_names = rawdata.textdata(2:end,1);
col_names = rawdata.textdata(1, 2:end);
data_mat = rawdata.data;
The row_names and col_names are cell array types. If you like them to be one string delimited by \t or ,, etc., you could use strjoin on them.

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);