您的位置:首页 > 编程语言 > MATLAB

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

2017-02-24 22:38 477 查看
在做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
1
M =csvread(filename)
 reads
acomma-separated value (CSV) formatted file into array 
M
. The file must contain only numeric values.
(2)M = csvread(filename,R1,C1) reads
data from the file startingat row offset R1 and column offset C1. For example, the offsets R1=0, C1=0specify
the first value in the file.
(3)M = 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=0, C1=0表示导入文件的第一个数值。
M = csvread(filename,R1,C1,[R1 C1 R2 C2]):导入CSV文件某个区域的数据,(R1,C1)为左上角坐标,(R2,C2)为右下角坐标。
举例如下:
创建一个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

 

(2)M = csvread(filename,2,0)

M =

 

     5    10    15    20

     7    14    21    28

(3)M = 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

 
 
 
 
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: