将CSV扫描到变量 [英] Scan CSV to variables

查看:178
本文介绍了将CSV扫描到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的CSV(一行):

  101,120,130 
 

pt_num = 101
x = 120
y = 130


解决方案

只需使用 csvread

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

您也可以使用 textscan 列在单元格数组中:

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

还有 fscanf 必须重新整形数组:

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

最后, dlmread csvread

  M = dlmread('filename.csv',' ,'); 


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

解决方案

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',',');

这篇关于将CSV扫描到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆