Writing Tables from Matlab into CSV - matlab

I have several tables in matlab that and I would like to write all to one .csv file, vertically concatenating. I would like to keep the column names from each table as the top row, and would like to use a loop to write the csv. The ultimate goal is to read the data in to R, but R.matlab did not work well. Suggestions about how to do this?
Alternatively how can I change filenames in a for loop using the iterator?
e.g. along the lines of
for i=1:10
writecsv('mydatai.csv',data(i))
end
So I must have at the end 10 csv files as output.

You can change the filename within the loop by using for sprintf string formatting function, for example:
dlmwrite(sprintf('mydata%i.csv', i), data(i) )
Note that the %i portion of the string is the sprintf formatting operator for an integer, it is just a coincidence that you also decided to name your iterator variable 'i'.
You can append extra data to an existing CSV by using the dlmwrite function, which uses a comma delimiter as the default, and including the '-append' flag.

Another way would be to use
writetable(Table,filename )
and to change file name after every alternation you can use
filename = ['mydata' num2str(i) '.csv']

Related

How to handle multiple delimiters in MATLAB

I am currently trying to read in .csv files that can have different delimiters. At the moment I am using readtable but that only handles one type and the use of textscan isn't really viable as the file contains 50+ columns.
The main two types of delimiter are ';' and ','. I am also using uigetfile in order for the user to select the file.
So I am wondering how I would go about handling more than one type of delimiter? The delimiter is consistent throughout each file and they all contain the same number of columns (hence my use of readtable).
Any suggestions would be greatly appreciated.
Thanks in advance.
I'd recommend you to unify delimiters. Eg. replace all semicolons with commas or vice versa, like that
file = 'bad_delimiters.csv';
fd = fopen(file);
text = fscanf(fd,'%c');
semicolons = strfind(text,';');
text(semicolons) = ',';
fd = fopen('good_delimiters.csv', 'w');
fwrite(fd, text);
If you have MATLAB version R2016b or later you can specify multiple delimiters for readtable by defining a set of import options, as illustrated in this example. You will first create a detectImportOptions object, change the 'Delimiter' property to a cell array of characters, then pass these options to readtable:
opts = detectImportOptions('your_file.csv');
opts.Delimiter = {';', ','};
T = readtable('your_file.csv', opts);

MATLAB export multiple .csv files at one time

I have a matrix where I need to export each column into a separate .csv file.
I know the number of columns and I can achieve my desired result if I specifically select one column to export. I would do this by:
dlmwrite('1.csv',data(:,1), 'precision', 9)
Therefore if I want column 2 I would change the variable to data(:,2) and save this as 2.csv.
So I want a loop that will do all this automatically. I have tried
for i=1:Number_of_Columns
dlmwrite('(i).csv',csv_data(:,(i)), 'precision', 9)
end
which clearly won't work but I am unsure how to do it.
Any help or advice would be much appreciated
Your problem is the filename. If you put i between quotes it will be taken as character instead of a variable. (In your case your filename will always be "(i).csv")
You can concatenate strings using [ ], and since i is an integer you have to convert it to string using num2str()
Try:
for i=1:Number_of_Columns
dlmwrite([num2str(i) '.csv'], csv_data(:,i), 'precision', 9)
end
PD: Since you are storing each column (not each row) in a file, I'm not sure if you want a file where each element is in a separate line, or if you want the column to be stored as a row and separated by commas.
If you want the latter, transpose your column:
dlmwrite([num2str(i) '.csv'], csv_data(:,i).', 'precision', 9)
Note that the transpose operator is .' instead of the complex conjugate ' (this is a common misuse since the results are the same as long as you only use real numbers)

read in semi colon separated CSV files

I have a CSV file which I want to read in using matlab.
I've tried using csvread but it does not seem to recognize the semi-colon as the delimiter. Is there any other way?
R;W
100;0.1
200;0.5
300;0.9
You can use dlmread instead and specify the delimeter to be a semi-colon. You will also want to set the row offset to 1 so you skip the first non-numeric row.
data = dlmread('filename.csv', ';', 1);

How to get the number of columns of a csv file?

I have a huge csv file that I want to load with matlab. However, I'm only interested in specific columns that I know the name.
As a first step, I would like to just check how many columns the csv file has. How can I do that with matlab?
As Jonesy and erelender suggest, I would think this will do it:
fid=fopen(filename);
tline = fgetl(fid);
fclose(fid);
length(find(tline==','))+1
Since you don't seem to know what kind of carriage return character (or character encoding?) is being used then I would suggest progressively sampling your file until you encounter a recognizable CR character. One way to do this is to loop over something like
A = fscanf(fileID, ['%' num2str(N) 'c'], sizeA);
where N is the number of characters to read. At each iteration test A for presence of carriage return characters, stop if one is encountered. Once you know where the carriage return is just repeat with the right N and perform the length(find...) operation, or alternately accumulate the number of commas at each iteration. You may want to check that your file is being read along rows (is it always?), check a few samples to make sure it is.
1-) Read the first line of file
2-) Count the number of commas, or seperator characters if it is not comma
3-) Add 1 to the count and the result is the number of columns in the file.
If the csv has only numeric value you can use:
M=csvread('file_name.csv');
[row,col]=size(M);

writing text file from MATLAB

I am trying to export a double array from MATLAB into a txt file. I can do this easily but the data is not structured how i need it. I need the data to be structured in the following way in the txt file;
-0.0195
-0.0217
-0.0260
-0.0274
-0.0258
-0.0246
-0.0244
-0.0233
-0.0209
-0.0221
Does anyone know how this would be done using dlmwrite?
Maybe something like this?
A=[-0.0195; -0.0217; -0.0260; -0.0274; -0.0258; -0.0246; -0.0244; -0.0233; -0.020;-0.0221];
dlmwrite('example.txt', A, 'newline', 'pc')
The last two argument determines the new line character used (CR or CR+LF), depending on the platform. Use 'pc' for the Windows version, and 'unix' for all others.
For full cross-platformness, you can use the isunix function, and have something like the following preceding your code:
if isunix==true
platform='unix'
else
platform='pc'
end
and then use the platform variable as the last argument in dlmwrite.
If your data is in a row-vector called A this will write it into a column in afile.txt:
dlmwrite('afile.txt',A,'\n')