如何在MATLAB中将来自两个不同单元阵列的数据存储到一个结构字段中



这是我的第一个:

假设我有一个结构

student_information=struct{'name','','surnames,''};

和两个单元阵列

possible_names=cell{'John','Amy','Paul'};
possible_surnames=cell{'Mitchell','Gordon','Maxwell'};

我需要用可能的名称单元格数组中的随机名称填充结构字段"名称",我认为:

for i=1:length(student_information)
 for j=1:length(possible_names);
 student_information(i).name=possible_names(randperm(j,1));
 end
end

但我需要在结构字段"姓氏"中填充两个可能的姓氏单元格数组中的随机姓氏(即"Gordon Maxwell")。。。我尝试了一种类似于我用来填写"姓名"字段的方法,但我没有。

我真的很感谢你的帮助

您的代码对TBH没有多大意义。您有一些语法错误。具体而言:

student_information=struct{'name','','surnames,''};

'surnames'需要一个结束引号。这也只分配一个结构。此外,struct是一个函数,但您正试图像使用单元数组一样使用它。你可能是这个意思:

student_information=struct('name','','surnames','');

除此之外:

possible_names=cell{'John','Amy','Paul'};
possible_surnames=cell{'Mitchell','Gordon','Maxwell'};

这是无效的MATLAB语法。cell是一个函数,但您试图将其引用为cell数组。改为:

possible_names={'John','Amy','Paul'};
possible_surnames={'Mitchell','Gordon','Maxwell'};

现在,回到您的代码。根据上下文判断,您希望从possible_surnames中随机选择两个名称,并将它们连接到一个字符串中。使用randperm,但生成两个选项,而不是像代码中那样的1。接下来,您可以通过使用sprintf并用空格分隔每个名称来作弊:

possible_surnames={'Mitchell','Gordon','Maxwell'};
names = possible_surnames(randperm(numel(possible_surnames),2));
out = sprintf('%s ', names{:})
out =
Gordon Maxwell 

因此,当你填充你的单元格数组时,你可以从possible_names数组中选择一个随机名称。首先,你需要用给定数量的插槽正确分配结构:

student_information=struct('name','','surnames','');
student_information=repmat(student_information, 5, 1); %// Make a 5 element structure
possible_names={'John','Amy','Paul'};
for idx = 1 : numel(student_information)
    student_information(idx).name = possible_names{randperm(numel(possible_names), 1)};
end

现在对于possible_surnames,执行:

possible_surnames={'Mitchell','Gordon','Maxwell'};
for idx = 1 : numel(student_information)
    names = possible_surnames(randperm(numel(possible_surnames),2));
    student_information(idx).surnames = sprintf('%s ', names{:});
end

让我们看看这个结构现在是什么样子的:

cellData = struct2cell(student_information);
fprintf('Name: %s. Surnames: %sn', cellData{:})
Name: Paul. Surnames: Maxwell Gordon 
Name: Amy. Surnames: Mitchell Maxwell 
Name: Paul. Surnames: Mitchell Gordon 
Name: John. Surnames: Gordon Maxwell 
Name: John. Surnames: Gordon Mitchell 

最新更新