How do I read comma separated doubles from text file into MATLAB?

176 views Asked by At

I have a text file called Output.txt that looks like this:

0.000000,0.550147,0.884956
1.000000,0.532486,0.847458
2.000000,0.501333,0.800000
3.000000,0.466418,0.746269
4.000000,0.409492,0.662252
5.000000,0.327257,0.520833
6.000000,0.267376,0.425532
7.000000,0.188427,0.296736
8.000000,0.115824,0.180505
9.000000,0.062768,0.099108

I need to read in the three values separated by commas into MATLAB as 3 different vectors. They can be called anything but C1, C2, and C3 could work.

C1 would contain [0.000000,1.000000,2.000000, ...], C2 would contain [0.550147,0.532486,...] and C3 would contain the values in the third column [0.884956,0.847458,...].

I tried using the following but I'm having problems getting it to work correctly:

File = 'Output.txt';
f = fopen(File, 'r');
C = textscan(f, '%f%f%f', 'Delimiter', ',');
fclose(f);

This gives me a 1x3 Cell array C but each of the cells in C are 1x100 and do not contain the correct numbers.

1

There are 1 answers

3
Adriaan On BEST ANSWER

You have a Comma Separated Value file, so you can simply use csvread to read in your matrix:

C = csvread('Output.txt');

where C now is a matrix containing all your values, which you can of course index through columns and rows. I'd recommend against creating the column vectors rather use C(:,1) for the first column etc.