如何将循环数据逐个保存到matlab中的excel文件中

时间:2011-07-16 02:19:48

标签: matlab matrix xls

我在Excel文件表1中有大量数据。列数是固定的(6)但有很多行。

对于每3行,我需要选出第2列的最小值并将整行保存到Excel文件或表2中,我将如何编写脚本?

item.xls(表1):

0.3 0.5 0.1 0.8 0.4 0.6
0.2 0.4 0.9 0.1 0.9 0.4
0.2 0.3 0.1 0.01 0.2 0.5
0.3 0.5 0.1 0.8 0.01 0.2
0.2 0.2 0.9 0.1 0.2 0.4
0.2 0.3 0.1 0.01 0.3 0.5
.......

在前3行中,第2列的最小值为0.3,然后将整行写入Excel文件的第2页。

然后接下来的3行,第2列的最小值为0.2,然后将整行写入Excel文件的第2页。

我想得到的结果是:

item.xls(sheet2):

0.2 0.3 0.1 0.01    % 1st 3 rows, the minimum value is 0.3 in 2nd column
0.2 0.2 0.9 0.1     % 2nd set of 3 rows, the minimum value is 0.2 in 2nd column
...

2 个答案:

答案 0 :(得分:1)

向下,对您的问题进行一些澄清将有助于找到更好的解决方案。根据我对您的问题的解释,以下内容可能有所帮助。我在这里生成随机测试数据。

% the number of test data rows
N = 12;

% generate some random vectors for testing
test1 = rand(N,1);
test2 = rand(N,1);
test3 = rand(N,1);
test4 = rand(N,1);

% create a temporary matrix to store the minimum of every
% 3 row set
final = zeros(N/3,4);

% loop in increments of 3
j = 1;
for k=1:3:N
    tmp = test2(k:k+2);

    % find the index of the minimum in this 3 row group of the 2nd col
    idx = find(tmp<=min(tmp));

    % offset idx to index into the original data properly
    idx = idx+k-1;

    % assign the "row" to the final variable
    final(j,:)=[test1(idx) test2(idx) test3(idx) test4(idx)];
    j = j+1;
end
% write the full results out at once
xlswrite('test.xls',final);

尝试一下,如果它不是您想要的,请发表评论以澄清您的问题。

答案 1 :(得分:1)

我将展示如何以矢量化方式从数据中提取相关行。我将把读/写excel文件的部分留给你(它应该是直截了当的):

%# sample data
data = rand(3*10,6);

%# for each three rows, find the min of second column, and get the row index
[r c] = size(data);
d = permute(reshape(data',[c 3 r/3]),[2 1 3]);  %'# split into third dimension
[~,idx] = min(d(:,2,:));                        %# find min of col2
idx = squeeze(idx) + (0:3:(r-1))';              %'# adjust indices

%# extract these rows from the data matrix
result = data(idx,:);