1

I have a CSV like this (one line):

101, 120, 130

How can I scan these into variables like this:

pt_num = 101
x = 120
y = 130
tshepang
  • 12,111
  • 21
  • 91
  • 136
Ben
  • 41
  • 2

1 Answers1

2

Just use csvread:

M = csvread('filename.csv');
pt_num  = M(:,1);
x = M(:,2);
y = M(:,3);

You can also use textscan to get each column in a cell array:

fid = fopen('filename.csv','r');
C = textscan(fid,'%d, %n, %n');
fclose(fid);

And there is fscanf, but you will have to reshape the array:

fid = fopen('filename.csv','r');
M = fscanf(fid,'%d, %f, %f')
fclose(fid);
M = reshape(M,3,[])';

Finally, dlmread, which works just like csvread:

M = dlmread('filename.csv',',');
chappjc
  • 30,359
  • 6
  • 75
  • 132
  • Thanks for the reply. I'm coming from C and was hoping there was something like this: fscanf (file, "%d %lf %lf", &pt_num, &x, &y). I'll be scaling up to larger matrices. Any other possibilities? – Ben Nov 22 '13 at 21:21
  • @Ben This will work for any number of lines. Notice the colon syntax in `M(:,1)` that gets all values in the first column. However, there is a `fscanf` in MATLAB if you want to go that route, this is just easier. – chappjc Nov 22 '13 at 21:26