Sulphur
Sulphur

Reputation: 584

How to convert m x n matrix to (each row as) comma separted text file in MATLAB?

I have a .mat file with m x n values. For simplicity, let's say we have 2 rows and 3 columns as:

2 4 6

2 1 4

I want to be able to export these values from .mat file to a text file, however, in such a manner that each line has the respective row from the .mat file with values in each row separated by comma. For the above example, in the txt file, it should look like:

2,4,6

2,1,4

This is what I did till now:

gt1 = load('Benchmark\AAmpiidata\groundtruth.mat');
r = gt1.gTruth.LabelData{1,1}{1,1};
allOneString = sprintf('%.0f,', r(1,:));
allOneString = allOneString(1:end-1);% strip final comma
fid=fopen('allOneString.txt','w');
fprintf(fid,'%s',allOneString);
fclose(fid);true 

I am able to extract the first row from .mat file as I require. I get this:

492,304,78,220

However, I don't know how to extract multiple rows from .mat file. Any help will be appreciated!

P.S. In the above code, in the .mat file gt1 directly doesn't have the values. The values I need (mxn) can be extracted using gt1.gTruth.LabelData{1,1}{1,1}

Upvotes: 0

Views: 63

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112729

Here's another way, which uses fprintf for file writing and strjoin for building the format string:

r = [2 4 6;2 1 4];
fid = fopen('allOneString.txt','w');
fprintf(fid, [strjoin(repmat({'%.0f'}, 1, size(r,2)), ',') '\n'], r.');
fclose(fid);

Upvotes: 0

Sulphur
Sulphur

Reputation: 584

There are two answers depending on the version of MATLAB you use.

Answer 1: For MATLAB 2018 and before:

gt1 = load('Benchmark\AAmpiidata\groundtruth.mat');
r = gt1.gTruth.LabelData{1,1}{1,1};
dlmwrite('allOneString.txt',r)

Answer 2: For MATLAB 2019 (2019-a as of writing this answer)

gt1 = load('Benchmark\AAmpiidata\groundtruth.mat');
r = gt1.gTruth.LabelData{1,1}{1,1};
writematrix(r,'allOneString.txt')

Upvotes: 1

Related Questions