如何打开多个文件,并将每个文档中的一行数据合并为一个数字? Matlab的 [英] How would I open multiple files, and combine one line of data from each document into a single number? Matlab

查看:292
本文介绍了如何打开多个文件,并将每个文档中的一行数据合并为一个数字? Matlab的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个文件都名为add_.txt,文件的编号从1 -5开始,我想从每个文件中获取第一行信息(由1到5组成的矩阵),将它们加在一起,获取信息并创建一个带有结果的新文本文件.显然答案是[5 5 5 5 5],但我想知道如何编程才能到达那里.

I have several files all named add_.txt with numbers from 1 -5 and I want to take the first line of information (a 1 by 5 matrix with all ones) from each file add them together, take this information and create a new text file with the result. Obviously the answer would simply be [5 5 5 5 5] but I would like to know how to program to get there.

我已经能够教自己如何从同一文档中添加"两个数据字符串,并使用此代码创建带有答案的文本文件

Ive been able to teach myself how to "add" two data strings from the same document and create a text file with the answer with this code

fid=fopen('add.txt');
A = fgetl(fid);
AA = str2num(A)
B = fgets(fid);
BB = str2num(B)
C = AA + BB;
fclose(fid);
dlmwrite('results.txt', C)

但是我不知道如何在多文件级别上跳转到自动计算,任何帮助都会很棒.

but i do not know how to make the jump to automated calculations on a multi-file level, any help would be great.

推荐答案

这种方法应该可以解决问题:

Something like this should do the trick:

% List of file names
% (can be auto-generated like so: filename = ['add_' num2str(ii) '.txt']
% with ii your iteration variable)
filenames = {'add_1.txt', 'add_2.txt', 'add_3.txt', 'add_4.txt', 'add_5.txt'};

% If you know the size of the first line: 
A = zeros(1,5);

% Loop through all filenames
for filename = filenames
    fid = fopen(filename{1});
    A = A + str2num( fgetl(fid) );%#ok
    fclose(fid);    
end

% Write results to file
dlmwrite('results.txt', A);

如果您事先知道A中有多少个元素,则必须对循环进行一些修改:

If you don't know beforehand how many elements there are in A, you'll have to modify the loop a little bit:

A = 0;
for filename = filenames
    fid = fopen(filenames{1});
    A = A + str2num( fgetl(fid) );%#ok
    fclose(fid);    
end

这篇关于如何打开多个文件,并将每个文档中的一行数据合并为一个数字? Matlab的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆