在matlab中读取CSV文件并将其设为2-d

时间:2011-09-16 05:47:07

标签: matlab file-io csv matrix

这是我想要做的一个例子:

我有一个CSV文件:

1,200,3,500...

2,400,4,600...

数据是成对的,即有交替的值x,y,x,y ......。

我想获取此输入并创建一个2d矩阵,其中矩阵值为 m = x-y 。输出应为CSV格式,带三倍x,y,m,x,y,m,....任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

@VladimirPerković的解决方案有正确的想法。我来解决一些小问题:

%# read CSV file
data = csvread('file.csv');
[r c] = size(data);

%# create output matrix
out = zeros(r,c/2*3);
out(:,1:3:end) = data(:,1:2:end);
out(:,2:3:end) = data(:,2:2:end);
out(:,3:3:end) = data(:,1:2:end) - data(:,2:2:end)

%# save as CSV file
csvwrite('out.csv', out)

创建的输出文件:

1,200,-199,3,500,-497,1,200,-199,3,500,-497
2,400,-398,4,600,-596,2,400,-398,4,600,-596
1,200,-199,3,500,-497,1,200,-199,3,500,-497
2,400,-398,4,600,-596,2,400,-398,4,600,-596

答案 1 :(得分:0)

这不是问题:

data = importdata('file.csv');
x = data(1:2:end); //number in the middle means you take every second sample
y = data(2:2:end);
m = x - y;

现在输出:

output_data = [x;y;m];
output_data = output_data(:);
csvwrite ('output.csv' , output_data);