将数据加载到矢量而不是MATlab中的单元格 [英] Loading data to vector rather than cell in MATlab

查看:76
本文介绍了将数据加载到矢量而不是MATlab中的单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码将文本文件中的数据加载到MATlab函数中:

I load data from text files into my MATlab function using this code:

data = cell(h.numDirs, numDataFilesInFirstDir);
for d = 1:h.numDirs
    % Code to set fileNames, iDir
    for t = 1:size(fileNames,1)
        fId = fopen([iDir, '/', fileNames{t}]);
        % Drop the first two lines (column headers)
        for skip = 1:2
            fgets(fId);
        end
        U_temp = fscanf(fId, '%f %f', [2, Inf]);
        U_temp = U_temp'; % ' transpose (syntax highlighting on SO)
        data(d, t) = {U_temp(:,2)};
        fclose(fId);
    end
end

每个文件应具有相同的长度(至少对于变化t,通常对于变化d,否则以后会出现问题)

The files should each have the same length (at least for varying t, usually for varying d or else I have problems later)

我应该(/如何)简化此处的代码,以避免(不必要?)单元格?

Should I be (/ How can I) simplify the code here to avoid (unnecessary?) cells?

我可以扫描第一个数据集,然后使用

I could scan the first data set, then use something like

data = zeros(h.numDirs, numDataFilesInFirstDir, lengthOfFirstFile)

但是我不知道这会不会更好.那是一个更好"的解决方案/方法吗?

but I don't know if that would be any better. Is that a 'better' solution/method?

推荐答案

我将使用dlmread而不是fscanf.数据类型很难,因为您的尺寸各不相同.我不会填充数组...不使用单元格所带来的任何好处都将被额外的复杂性和内存占用所克服.单元阵列是一个合理的选择.实际上,在这种情况下,我不必担心过多的预分配.以下是使用structs的类似选项,其动态字段名称嵌入了源目录和文件名,以供以后参考.

I would use dlmread instead of fscanf. Data type is hard since your dimensions vary. I wouldn't pad arrays... any benefit from not using cells would be overcome by the extra complexity and memory hit. Cell arrays are a reasonable choice. I wouldn't worry about preallocation too much in this case actually. Below is a similar option using structs with dynamic field names that embed the source directory and filename, for later reference.

data = struct();
for d = 1: ...
    for t = 1: ...
        file = fullfile(iDir, fileNames{t});
        range = [3, 1, inf, 2];
        dlm = ' ';
        Utemp = dlmread(file, dlm, range);
        data.(iDir).(fileNames{t}) = Utemp(:, 2);

这篇关于将数据加载到矢量而不是MATlab中的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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