【问题标题】:how to save looping data one by one into excel file in matlab如何将循环数据一一保存到matlab中的excel文件中
【发布时间】:2011-10-06 14:09:23
【问题描述】:

我在 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文件的sheet 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
...

【问题讨论】:

    标签: matlab matrix xls


    【解决方案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,:);
    

    【讨论】:

    • 关于 [2 1 3] 的问题..这是什么意思?
    • 从您的描述中不清楚您是要获取整行还是仅获取前四列。对于后者,将我代码中的最后一行更改为:result = data(idx,1:4);
    • @down:整行(带有 [2 1 3])将元素重新排列为 3D 矩阵,使得每三行都在一个切片中。阅读此问题以了解:stackoverflow.com/questions/1390909/…
    【解决方案2】:

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

    % 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);
    

    试试这个,如果它不是你想要的,发表评论来澄清你的问题。

    【讨论】:

    • 我已经编辑了这个问题..但是这个想法是正确的..但是,我不知道如何从 excel 文件中读取数据...'final(j,:)=[test1 (idx) test2(idx) test3(idx) test4(idx)];' test1(idx) 是第 1 列,我该如何替换它?请指教..谢谢..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    相关资源
    最近更新 更多