将csv文件在MATLAB中导入为向量的csvread函数以及将向量导出到csv文件中的csvwrite函数

在做kaggle练习赛时,遇到了要将csv文件在MATLAB中导入为向量,以及将向量导出到csv文件中的问题。

其实解决这两个问题很简单,MATLAB有现成的函数,但是当你不知道具体是哪个函数时,会比较头疼。特此做记录如下,希望对大家有所帮助。

1:将csv文件在MATLAB中导入为向量

要用到MATLAB中的csvread()函数,官方文档如下:

·        M = csvread(filename)

·        M = csvread(filename,R1,C1)

·        M = csvread(filename,R1,C1,[R1 C1 R2 C2])

Description

1M =csvread(filename) reads acomma-separated value (CSV) formatted file into array M. The file must contain only numeric values.

2M = csvread(filename,R1,C1) reads data from the file startingat row offset R1 and column offset C1. For example, the offsets R1=0C1=0specify the first value in the file.

3M = csvread(filename,R1,C1,[R1 C1 R2 C2]) reads only the range bounded byrow offsets R1 and R2 and column offsets C1 and C2. Another way to define the range is to use spreadsheetnotation, such as 'A1..B7' instead of [0 0 6 1].

解释如下:

M = csvread(filename)导入一个CSV格式的文件,转换为向量M。文件必须是数值类型。

M = csvread(filename,R1,C1)CSV文件的第R1行,第C1列导入数据,例如R1=0C1=0表示导入文件的第一个数值。

M = csvread(filename,R1,C1,[R1 C1 R2 C2])导入CSV文件某个区域的数据,(R1C1)为左上角坐标,(R2C2)为右下角坐标。

举例如下:

创建一个CSV文件(以逗号分隔的文件),文件名为test.csv,文件内容如下:

   02, 04, 06, 08
   03, 06, 09, 12
   05, 10, 15, 20
   07, 14, 21, 28

读文件:filename= 'test.csv';(文件要在当前路径下,或者用绝对路径)

(1)  M = csvread(filename)
得到的结果是:
M =
 
     2     4     6     8
     3     6     9    12
     5    10    15    20
     7    14    21    28
 
2M = csvread(filename,2,0)
M =
 
     5    10    15    20
     7    14    21    28
3M = csvread(filename,1,0,[1,0,2,2])
  M =
 
     3     6     9
     5    10    15

 

2将向量导出到csv文件中:

用到的MATLAB函数是csvwrite(),具体用法与csvread()相同,贴出官方文档,不再做具体描述。

csvwrite

Writecomma-separated value file

Syntax

csvwrite(filename,M)
csvwrite(filename,M,row,col)

Description

csvwrite(filename,M) writesmatrix M into filename ascomma-separated values. The filename input is astring enclosed in single quotes.

csvwrite(filename,M,row,col) writesmatrix M into filename startingat the specified row and column offset. The row and column arguments are zerobased, so that row=0 and C=0 specifythe first value in the file.

Examples

Thefollowing example creates a comma-separated value file from the matrix m.

m = [3 6 9 12 15; 5 10 15 20 25; ...
     7 14 21 28 35; 11 22 33 44 55];
 
csvwrite('csvlist.dat',m)
type csvlist.dat
 
3,6,9,12,15
5,10,15,20,25
7,14,21,28,35
11,22,33,44,55

The next example writes the matrix to the file, starting at a column offset of 2.

csvwrite('csvlist.dat',m,0,2)
type csvlist.dat
 
,,3,6,9,12,15
,,5,10,15,20,25
,,7,14,21,28,35
,,11,22,33,44,55

 

 

 

 

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值