美文网首页
【研究工具】Matlab批量数据处理

【研究工具】Matlab批量数据处理

作者: 子夜Uni | 来源:发表于2021-04-20 09:44 被阅读0次

学习的实验往往会记录大量的原始数据,excel处理起来很不方便,好在都是格式化的,用matlab编写了一个方法,方便自己在不同场景套用。

读写格式化的数据文件(用数据类型table的方法)

% data analysis: 6 contexts;seperation data from different contexts
function contextSeperation(subName)
    % subName = '6001_jushanzhong';

    %curFile = fopen([subName,'.txt'],'r');
    matData = readtable([subName,'.txt']);

    % correct error in former recording
    errData = matData.Error;
    for i = 1 : length(errData)
        if errData(i) < - 180
            errData(i) = errData(i) + 360;
        end
    end
    matData.correctedErr = errData;

    % add new row 'rotation'
    matData.bias = matData.RealTarget-matData.ShowTarget;

    % add new row 'subjectName'
    f = @(x) subName;
    cellName = cell(length(errData),1);
    cellName = cellfun(f,cellName,'UniformOutput',false);
    matData.subName = cellName;

    arrCenter = matData.CenterInd;
    uniqCenter = unique(arrCenter);
    numCenter = length(uniqCenter);

    newTrialList = [1:10 1:40 1:10]';

    % 按序号分出来
    for k = 1 : numCenter
        tmpInd = find(arrCenter == uniqCenter(k));
        tmpArr = matData(tmpInd,:);
        tmpArr.Trial = newTrialList;
        writetable(tmpArr,['seperate\',subName,'_',num2str(k),'.txt'],'Delimiter','\t');
    end
end

批处理文件夹中所有同类文件

% 读取目录下所有的文件信息
fileList = dir(cd);
listLength = length(fileList);

for i = 1 : listLength
    if ~fileList(i).isdir
        full_name = [cd,'\',fileList(i).name];        
        [pathstr,name,ext] = fileparts(full_name); % 获取需要处理的文件文件名和拓展名
        if strcmp(ext,'.txt')
            contextSeperation(name);
        end
    end
end

合并文件夹中所有数据文件

之前数据量小的文件一直都用的批处理.bat来合并,最近数据量大了这个功能总是出问题,还是自己写一个比较放心。

fileList = dir(cd);
listLength = length(fileList);

C = [];

for i = 1 : listLength
    if ~fileList(i).isdir
        full_name = [cd,'\',fileList(i).name];        
        [pathstr,name,ext] = fileparts(full_name); % 获取需要处理的文件文件名和拓展名
        if strcmp(ext,'.txt') % 要拼合的文件类型
            tmpTable = readtable(full_name);
            if isempty(C)
                C = tmpTable;
            else
                C = [C; tmpTable];
            end
            
        end
    end
end
writetable(C,'STS_all.txt','Delimiter','\t');

相关文章

网友评论

      本文标题:【研究工具】Matlab批量数据处理

      本文链接:https://www.haomeiwen.com/subject/forylltx.html