【问题标题】:creating a structure within a structure from imported text files in matlab从matlab中导入的文本文件在结构中创建结构
【发布时间】:2012-02-23 23:08:28
【问题描述】:

我不确定是否有人可以帮助解决这个问题,但我们开始吧。我有 4 个文件夹,每个文件夹包含不同位置的数据,在文件夹中我有 8 个 .txt 文件,它们代表每个位置的测量变量(即每个位置测量的相同变量)。我正在尝试将这些导入matlab并在结构中列出测量变量,以便之后可以将它们相互比较和绘制(不这样做,它们将相互覆盖)。

我已经编写了一个脚本,用于将这些导入matlab,该脚本可以正常工作,但并不完全按照我想要的方式,脚本如下:

clear all
pathName = 'E:\University\CEH Lancaster\Project\LA practice\final files';
FolderListing = dir(pathName);  
FolderListing = FolderListing(3:end);
    %lists the folder in the directory specified by pathName
for i = 1:length(FolderListing);
    LName{i} = (FolderListing(i).name);
        %obtains the name of each folder
end

for i = 1:length(LName)
    TopFolder{i} = fullfile(pathName,LName{i});
        %path for each individual folder 
    dirListing{i} = dir(fullfile(TopFolder{i},'*.txt'));  
        %list of the .txt files
    for ii = 1:length(dirListing{1,1});
        fileToRead1{1,i}{ii,1} = (dirListing{1,i}(ii,1).name);
        %name of the .txt files in the TopFolder
    end
end

for i = 1:length(fileToRead1);
    for ii = 1:length(fileToRead1{1});
    fid{1,i}{ii,1} = fopen((fullfile(TopFolder{1,i},fileToRead1{1,i}{ii,1})));
        %open the files specified by fileToRead prior to importing the data
        %into matlab
    data{1,i}{ii,1} = textscan(fid{1,i}{ii,1},'%f');
        %import the data into matlab
    [~,name{1,i}{ii,1}] = fileparts(fileToRead1{1,i}{ii,1});
        %obtain the name of each of the variables
    Location.(LName{i}).(genvarname(name{1,i}{ii,1})) = data{1,i}{ii,1};
        %create a strucutre for the individual locations and the
        %variables.
    end
end

问题在于最终结果,而不是 Location.Name 和变量列表,我有 Location.Name.variables,这似乎没有必要。我意识到这是由于我编写脚本最后一行的方式,但我似乎无法在不产生错误的情况下更改它。您可以就问题或一般脚本提供任何建议,我们将不胜感激。

【问题讨论】:

  • 我不太确定我是否理解您喜欢哪种格式。是您拥有Location.Alaska.temp = 1;Location.Alaska.lat = 5;Location.Alaska.lon = 3; 而您更愿意拥有Location.Alaska = [1 3 5]
  • 目前我说的是 Location.Alaska.temp{1,1} 而不是我希望 temp 不是 1x1 单元格,而只是值。例如,目前如果我将 Location.Alaska.temp 写入命令窗口,matlab 返回 [365x1 double],而不是我希望它返回向量。

标签: matlab structure cell


【解决方案1】:

我认为 cell2mat 是您为此目的所需的功能。这是我的用法,看看是否符合你的需求:

tt = {ones(1,100)};
tt
tt = 

    [1x100 double]
cell2mat(tt)
    ans =

      Columns 1 through 15

         1     1     1     1     1     1     1     1     1     1     1     1...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多