Add a delimiter to end of each line of csv file MATLAB - matlab

I am appending to a csv file. The current code outputs a line: a;b;c;d
I need it to output a;b;c;d;
notice the extra ';' at the end of d. That is essential
matrix = [a,b,c,d]
dlmwrite('matrix.csv', matrix, 'delimiter',';','-append','roffset',0, 'precision',14)
any help would be appreciated.
I have had to keep variables a,b,c and d as numbers, or it makes it a character vector (or something) which makes my csv look funny

I've always had problems with the MatLab inbuild CSV writing methods. Why don't you code your own .CSV writing method?
Here, you could make a function something like:
function write_to_csv(filepath, matrix)
csv = fopen(filepath, 'a+'); % check what sort of open you'd like : https://uk.mathworks.com/help/matlab/ref/fopen.html#inputarg_permission
for ii = 1 : numel(matrix) % this loop depends on the dimensions of your matrix
fprintf(csv, '%s;', matrix(ii)); % check fprintf return type, depending on the data in the matrix : https://uk.mathworks.com/help/matlab/ref/fprintf.html?searchHighlight=fprintf&s_tid=doc_srchtitle#inputarg_formatSpec
end
fclose(csv);
end
This works for a 1D matrix you've supplied, run with:
write_to_csv('matrix.csv',matrix)

Related

Outputting a word file using Matlab

I want to write a function that takes number n as input, then outputs a tab separated word document that looks like 5 rows of:
1 2 3...n n n-1 n-2 ..1
Let me tell you what I have tried already: It is easy to create a vector like this with the integers I want, but if I save a file in an ascii format, in the output the integers come out in a format like " 1.0000000e+00".
Now I googled to find that the output can be formatted using %d and fprintf, but given the row length is part of the input, what would be the most efficient way to achieve it?
maybe something like this:
Nrow = 5;
N = 10;
dlmwrite('my_filename.txt', repmat([1:N, N:-1:1], Nrow, 1), 'delimiter', '\t', 'precision', '%d');
If you mean a normal *.txt kind of file, I would normally use a for loop with fprintf(fileid,'%d things to print',5), with the appropriate fopen(.) statement. You'd be surprised what a good job fopen with 'w' and 'a' does. Try it and let us know!
In response to rayryeng: You are right! Here is a sample of code for writing a matrix to file using fprintf, without a for-loop.
A=rand(5);
fid=fopen('Rand_mat.txt','w');
fprintf(fid,'%0.4f %0.4f %0.4f %0.4f %0.4f\n',A');
fclose (fid);
where A is transposed because MATLAB reads the columns of the matrix first.
Thanks!

load txt dataset into matlab in a matrix structure

I need to read a txt dataset and do some analytics by matlab. the structure of the txt file is like this:
ID Genre AgeScale
1 M 20-26
2 F 18-25
So, I want to load this txt file and build a matrix. I was wondering if someone could help me with this. I used fopen function but it gives me a single array not a matrix with 3 columns.
MATLAB has an interactive data importer. Just type uiimport in the command window. It allows you to:
Name the variable based on heading as shown in your example. You can also manually change them.
Specify variable (column) type, e.g. numeric, cell array of strings, etc.
Auto generate an import script for next use (if desired)
If it works for you then congratulations, you don't need to waste hours to write an data import script :)
Function fopen only returns the file ID and not the content of the file. Once you open the file you use the file ID to read line by line and then parse each line with strsplit using space as the delimiter.
Here's one simple way of doing so:
fid = fopen('textfile.txt');
tline = fgetl(fid);
n = 1;
while ischar(tline)
data(n,:) = strsplit(tline(1:end-1),' ');
n=n+1;
tline = fgetl(fid);
end
fclose(fid);
Keep in mind that the matrix data is type string and not numeric, so if you want to use the numeric values of your dataset, you'll need to take a look at the functions str2num (str2double in newer versions) and strtok to split the AgeScale strings with delimiter '-'.

adding a matrix with appending using dlmwrite in matlab

I need to write two different matrices in a file. However, first matrix is just initial values=> 25*ones(10,10). Second matrix is also 10x10 matrix , and updating in every iteration. My question is , first matrix will be on the beginning of the file, later on second matrix will be appending the end of the first matrix after each iteration and updating. I dont want to overwrite the second matrix everytime, which is happening when i run these codes
My codes are like this:
if ss==5000;
dlmwrite('d:\Temp.txt',Tin*ones(10,10), ' ');
dlmwrite('d:\Temp.txt', Tnew,'-append','roffset', 1, 'delimiter', ' ');
ss=0
end
Could you help me on this ?
Thanks in advance.
I've put together a complete example that demonstrates what I think you want.
If the file doesn't exist, it creates it and puts your first matrix inside it. If it does exist, it appends subsequent data
filename = 'd:\Temp.txt';
for ss=1:25000
if mod(ss,5000)==0
%generate some data to write
Tnew = rand(10,10);
if ~exist(filename,'file')
dlmwrite(filename,ones(10,10), ' ');
end
dlmwrite(filename, Tnew,'-append','roffset', 1, 'delimiter', ' ');
end
end

csvwrite in loop with numbered filenames in matlab

kinda new to matlab here, searching the csvwrite tutorial and some of the existing webportals regarding my question couldn't find a way to pass my variables by value to the output file names while exporting in csv; providing my bellow scripts, i would like to have the output files something like output_$aa_$dd.csv which aa and dd are respectively the first and second for counters of the scripts.
for aa=1:27
for dd=1:5
M_Normal=bench(aa,dd).Y;
for j=1:300
randRand=M_Normal(randperm(12000,12000));
for jj = 1:numel(randMin(:,1)); % loops over the rand numbers
vv= randMin(jj,1); % gets the value
randMin(jj,j+1)=min(randRand(1:vv)); % get and store the min of the selction in the matix
end
end
csvwrite('/home/amir/amir_matlab/sprintf(''%d%d',aa, bb).csv',randMin);
end
end
String concatenation in MATLAB is done like a matrix concatenation. For example
a='app';
b='le';
c=[a,b] % returns 'apple'
Hence, in your problem, the full path can be formed this way.
['/home/amir/amir_matlab/',sprintf('%d_%d',aa,bb),'.csv']
Furthermore, it is usually best not to specify the file separator explicitly, so that your code can be implemented in other operating systems. I suggest you write the full path as
fullfile('home','amir','amir_matlab',sprintf('%d_%d.csv',aa,bb))
Cheers.

In Matlab, how do you execute an fprintf command on an arbitrarily large matrix

I am working on analysis of a large data set using matlab. I would like to be able to run something along the lines of the fprintf command on this matrix, which has about 22000 columns. So, here is what I had in mind so far:
j=22;
for i = 1:j;
fname = fopen(strcat('chr', num2str(i), '.out'), 'r');
A = fscanf(fname, '%d', [1000,inf]);
FIDW = fopen(strcat('chrproc', num2str(i), '.out'), 'w+');
fprintf(FIDW, '%d\t%d\t%d\t%d\t%d\t%d\t\n', B);
end
there are 22 files this size that will be turned into matrices via lines 1-4. However, the tricky part (at least for me) is that fprintf asks you for the FORMAT. Because these files are so large, there is no real way to enter in %d\t.
Perhaps the fgetl command is better? But fgetl does not print to a file, and more importantly, fgetl returns a string, which does not work well for me. Really, something like the fscanf command would be great, except that reads instead of printing...
Thank you very much for your help and advice.
You may use one of the options described in this matlab doc. The possibilities are:
save -ascii (beware of the scientific notation)
dlmwrite
fprintf as you mentionned, with having format defined as fmt = repmat('%d\t',1,8); (8 to be replaced by your actual number of columns)
Alternatively, you can use the following File Exchange function called saveascii.
Marsei's answer is correct. However in matlab coder I had to take a different approach (works in regular matlab also):
function printmatrix(matrix)
matrix = matrix';%transpose
[rows, cols] = size(matrix);
format=['%-10g ' 0];
for i=1:cols
for j=1:rows
fprintf(format,matrix(j,i));%Flipped because of matlab
end
fprintf('\n');
end
fprintf('Size of matrix: %g x %g\n', cols, rows);%Backwards because we invert it.
end
See:
https://stackoverflow.com/questions/38601352/how-to-print-a-matrix-in-matlab-coder
This also works (but not in matlab coder):
m=magic(5);
[rows cols] = size(m);
x = repmat('%4.0f\t',1,(cols-1));
fprintf([x,'%4.0f\n'],m');