dlmwrite a matrix into an existing csv file

14 views (last 30 days)
Dear All,
I do have a a csv file which is basically a 5*6 matrix like the following one:
test.cvs = [1 2 3 4 5 6
2 3 4 5 6 7
3 4 5 6 7 8
4 5 6 7 8 9
5 6 7 8 8 8]
Then, I want to dlmwrite the matrix q and at the same time append the data that had been already existed in the csv file. However, I do not want to add matrix q as the 7th row! I like to dlmwrite matrix q in the following way:
q = [11 12 12 12 13]
test.csv = [1 2 3 4 5 6 11 12 12 12 13
2 3 4 5 6 7 0 0 0 0 0
3 4 5 6 7 8 0 0 0 0 0
4 5 6 7 8 9 0 0 0 0 0
5 6 7 8 8 8 0 0 0 0 0 ]
I know that we can use the below command to append by column but I wonder if there is way to append in the way I want it?
dlmwrite('test.csv', q, 'delimiter', ',', 'precision', 9 ,'-append')
Thanks.

Accepted Answer

Walter Roberson
Walter Roberson on 12 Feb 2016
Try
dlmwrite('test.csv', q, ',', 1, 7, 'precision', 9)
You might have to fill out q with rows of 0's.
  3 Comments
Homayoon
Homayoon on 12 Feb 2016
And also the command does not work! Gave me an error.
Walter Roberson
Walter Roberson on 12 Feb 2016
Edited: Walter Roberson on 12 Feb 2016
'delimiter' is positional when you use that form of row and column offset.
dlmwrite('FILENAME',M,'DLM',R,C) writes matrix M starting at
offset row R, and offset column C in the file. R and C are zero-based,
so that R=C=0 specifies the first value in the file.
However it turns out that if you do not use -append then it still erases the file, and that if you do use -append then it goes to the end of the file and writes after that, not appending in-place.
The solution would appear to be to use xlswrite() if you are using an MS Windows system with Excel installed. If you are using Linux or OS-X or do not have Excel installed, then xlswrite() operates in Basic mode that ignores the position offsets and so would not work for this situation.
Universal work around: read the existing data, put the new content onto the side of that, write out the augmented data.
data = csvread('test.cvs');
data(1,end+1:end+length(q)) = q;
dlmwrite('test.cvs', data, 'Delimiter', ',', 'Precision', 9);

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!