【问题标题】:Sorting and taking average in textfile在文本文件中排序和取平均值
【发布时间】:2014-02-22 09:17:41
【问题描述】:

我有两个这样的文本文件:

文件 1.txt

Size   Iterations
3        45
5        6
7        50
1        34
5        56
1        4

文件2.txt

Size   Iterations
3        5
5        6
7        6
1        3
5        6
1        4

我想先做两件事:

1) 根据大小对两个文件进行排序。

文件 1.txt

Size   Iterations
1        34
1        4
3        45
5        6
5        56
7        50

文件2.txt

Size   Iterations

1        3
1        4
3        5
5        6
5        6
7        6

2)一旦文件根据大小排序,我想创建一个新文件并存储与每个唯一大小编号对应的所有迭代的平均值

像这样:

Size  Average
1      3.5  
3      5
5      6
7      6

我是 MATLAB 新手。请指导我遵循哪些功能来完成上述任务。

【问题讨论】:

  • 我不明白您如何根据 SizeIterations 生成 Average 值!或者它们是否相关!
  • 行标签是否分开?
  • @Mohammad 我想取每个唯一尺寸编号对应的所有迭代的平均值
  • 所以这将是 (34+4+3+4)/4 等于 11.5。你最好编辑你的问题。
  • @phyrox 它们是三个空格分隔的。

标签: matlab


【解决方案1】:

我推测 file1.txtfile2.txt 中的第一个 raw 不存在。我的意思是那些包含 ASCII 字符的行。

clear all
a = load('file1.txt');
b = load('file2.txt');
c = [a;b]; % appends file2 below file1

[aa I] = sort(c(:,1)); % you can find sorted IDs in I
ids = unique(c(I,1));
ave = zeros(1,ids);
for i=1:length(ids)
    currentIds = I(c(I,1) == ids(i)); %boolean indexing in sorted IDs
    ave(i) = mean(c(currentIds,2));
end
disp([ids,ave'])

【讨论】:

  • 效果很好。你能解释一下这段代码是如何计算平均值的吗?
  • 这很简单!在 for 循环中,我们有:一组属于 i_th _Size 的索引是从包含已排序索引的向量 I 中指定的。现在 _currentIds 中存在的 i_th Size 行的索引引导我们计算平均值。这可以通过索引 c 矩阵来实现。
【解决方案2】:

您可以使用此代码:

%1-Sort everything
s1 = tdfread('File1.txt','   ');%Three space separation
[sorted_s1_size,sorted_s1_idx]=sort(s1.size,'ascend');
sorted_s1_iterations = s1.iterations(sorted_s1_idx);

s2 = tdfread('File2.txt','   ');
[sorted_s2_size,sorted_s2_idx]=sort(s2.size,'ascend');
sorted_s2_iterations = s2.iterations(sorted_s2_idx);

%2-Get the average

sizes = [sorted_s1_size;sorted_s2_size];
iterations = [sorted_s1_iterations,sorted_s2_iterations];

unique_sizes = unique(sizes);
avg_iterations = zeros(1,length(unique_sizes);
for i=1:length(unique_sizes)
  w_size = unique_sizes(i);
  w_idx=find(sizes==w_size);
  avg_iterations(i) = mean(iterations);
end

%4-Write the file
fid = fopen('output.txt','w');
for k=1:length(unique_sizes)
   fprintf(fid,'.2f\t%.2f\n',unique_sizes(i),avg_iterations(i));
end
fclose(fid);

您可以优化它删除两个排序操作(unique 也按 id 排序)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多