首页 > 解决方案 > 在循环中创建结构

问题描述

我有几个文件夹。在每个文件夹中都有一个名为 Data 的文件。每个文件都有结构,其中之一是 Data.ensemble。从这个结构中,我提取了温度(第 9 列,请参阅问题Hierarchy between and / or in an if statement)。我现在的问题是在我的循环中,每次迭代都提取并保存这个温度在一个结构中。例如,如果我有 10 个文件夹和 10 个文件。我想

Temperature.1=[12 15 10...]
Temperature.2=[20 30 11...]
...
Temperature.10=[15 26 27...]

这些都是不同的大小。提取工作正常,保存它是一个问题。我在https://nl.mathworks.com/matlabcentral/answers/304405-create-a-struct-iteratively的帮助下尝试了以下代码

folders =struct2cell(dir(Pathfolders)); %Pathfolders is the path to the folders
NaamFolders=string(char(folders(1,:))); %make a list of all the foldernames
lenNF=length(NaamFolders);

for i = 1:lenNF
    Map=char(NaamFolders(i,1)); % Give me the name of the first , second, ... folder
    Pathfiles=[Path,'\',Map,'\','*_new.mat']; %Make the path to the files that end with _new.mat (in my case only 1)
    files =struct2cell(dir(Pathfiles)); %Select all files that end with _new.mat (in my case only 1)
    NaamFiles=char(files(1,:)); % Make a list of the names of all those files (in my case only 1)
    FilePath=[Path,'\',Map,'\',NaamFiles]; %create path to that 1 file
    Data=load(FilePath); %load that file
    [lenData,lenvariables]=size(Data.ensemble) % determine the size of the file structure called ensemble
    idx=NaamFolders{i} %Select the name you want to call your structure in the variable you want to create
    index = ismember(Data.ensemble(:,8),[10,20,30]) & Data.ensemble(:,5) == 12; %determine the index where  column 5 == 12 and column 8 == 10 or 20 or 30
    RightData   = Data.ensemble(index,:) % this the data where the previous comment is true
    Temperature.idx=RightData(:,9) % this line does not work. For every iteration, create a new structure within temperature that extracts column 9 from RightData.

end

这是最后一行不起作用并给出错误

Unable to perform assignment because dot indexing is not supported for variables of this type.
Error in ExtractTrajectory (line 36)
    Temperature.idx=RightData(:,9)

标签: matlabloopsstructure

解决方案


  • 变量名应始终以字母开头
  • 不允许使用空格数字、特殊字符如~、#、% 。

检查NaamFolders格式或为我们打印格式。

如果它以数字开头,您可以做的就是向所有 NaamFolders 列表元素添加一个给定的字母,如下所示

NaamFolders = strcat('z',NaamFolders)

结构字段格式要求


案例1: 字母开头

>> isvarname("folder1")

ans =

  logical

   1

可以与点赋值一起使用

>> check.("folder1") = 5

check = 

  struct with fields:

    folder1: 5


案例2: 数字开头


>> isvarname("1folder")

ans =

  logical

   0

不能与点赋值一起使用

>> check.("1folder") = 5
Invalid field name: '1folder'.

案例3: 空格开始

>> isvarname("    folder")

ans =

  logical

   0

不能与点赋值一起使用

>> check.("    folder") = 5
Invalid field name: '    folder'.

案例4: 特殊字符开头

>> isvarname("#folder")

ans =

  logical

   0

不能与点赋值一起使用

>> check.("#folder") = 5
Invalid field name: '#folder'.

推荐阅读