I have a txt file containing a Matrix separated by commas. I would like to add a comma after the last column on every row.

8 views (last 30 days)
I have a .txt file containing >200'000 rows and 12 columns separated by commas (only numbers, no characters). I would like to add a comma after the last column on every row without adding any values in a 13. column. (example below).
example of what I have:
1,2,3,4,5,6,7,8,9,10,11,12
1,2,3,4,5,6,7,8,9,10,11,12
example of what I am trying to get:
1,2,3,4,5,6,7,8,9,10,11,12,
1,2,3,4,5,6,7,8,9,10,11,12,
Thank you already for your time.

Accepted Answer

dpb
dpb on 28 Apr 2022
Edited: dpb on 30 Apr 2022
data=readlines('yourfile.txt'); % read file as string array
data=data(strlength(data)>0); % save only non-empty lines
data=strcat(data,","); % catenate "," on end
writematrix(data,'yournewfile.txt','QuoteStrings',0) % write back out, don't quote
  4 Comments
dpb
dpb on 28 Apr 2022
Edited: dpb on 30 Apr 2022
I did just check -- it is, indeed, whether or not there is that last newline or not.
The above fix will remove it if is there in the original; leaving it out will produce the extra ','; a little extra logic could have both by testing if there is a blank line and only appending the ',' to those lines that are longer.
data=readlines('yourfile.txt'); % read file as string array
ix=strlength(data)>0; % find non-empty lines
data(ix)=strcat(data(ix),","); % catenate "," on end
writematrix(data,'yournewfile.txt','QuoteStrings',0) % write back out, don't quote

Sign in to comment.

More Answers (0)

Categories

Find more on Numeric Types in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!