0

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.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
user3716193
  • 476
  • 5
  • 21

1 Answers1

5

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.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • I have tried this previously and it did not work as you have explained. I know that I have a comma separated value file but when I use csvread it gives me a 1x100 vector. I think there might be a problem with the decimal values of my file. – user3716193 Dec 14 '16 at 22:40
  • with the file you present this works for me. Can you please post a [mcve] which outlines why it doesn't work for you? – Adriaan Dec 15 '16 at 06:58
  • I figured out my problem, Matlab was having a problem finding my file on my computer. I used an exact path to my file inside the csvread(path/to/my/file) command and it worked. Thanks. – user3716193 Jan 30 '17 at 20:51