Matlab - 如何将一组元胞数组转换为允许索引的数组?

Matlab - How can I transform a set of cell arrays into an array that allows indexing?

我为这个问题苦苦挣扎了一天,在网上找不到任何解决方案。我有四个单元格数组,每个国家/地区都有数据,我在这些单元格数组上执行操作以查找我想要分析的多个国家/地区。我已将这些国家/地区保存在一个 27x1 元胞数组中,该数组具有非数值属性,其输出如下所示:

'Belgium'
'Bulgaria'
'Croatia'
'Cyprus'
'Czechia'
'Denmark'
'Estonia'

这是我想从其他元胞数组中减去每个国家/地区数据的行示例。问题是元胞数组不允许索引,这意味着我不能使用它们从其他元胞数组中减去数据。 所以我想要的输出是一个允许索引的数组,这样我就可以使用该数组减去其他元胞数组的信息。

我尝试过的:

我是新来的,所以我不知道如何附加我的 .m 文件和元胞数组。因此,我在这里添加了一部分代码:

[~,ia,ib] = intersect(pop(:,1),gdp(:,1));
Com_popgdp = [pop(ia,1:2),gdp(ib,2)];

[~,ia,ib] = intersect(fp(:,1),lr(:,1));
Com_fplr = [fp(ia,1:2),lr(ib,2)];

[~,ia,ib] = intersect(Com_popgdp(:,1),Com_fplr(:,1));
Com_all = [Com_popgdp(ia,1:2),Com_fplr(ib,2)]; 

Com_all = Com_all(:,1);

%Com_all is the resulting cell array with all countries that I want to
%analyse resulting from the intersections of cell arrays. For the analysis, 
%I must extract the Com_all rows from
%pop/gdp/fp/lr. However, this is not possible with cell arrays. How can I
%access and extract the rows from pop/gdp/fp/lr for my analysis?

谁能帮我找到一种方法,可以使用选择元胞数组作为索引从其他元胞数组中减去数据? 哪种方法合适?

有一个比我最初想象的更简单的解决方案。

首先,将我们的元胞数组更改为表格

gdp = cell2table(gdp,'VariableNames',{'country','gdp'})

或者您可以直接将它们读入表格 (https://www.mathworks.com/help/matlab/ref/readtable.html)。

只要所有表的列名称与国家/地区名称相同,您就可以使用 innerjoin 它是基于国家/地区的表的交集。

下面是我运行测试的例子:

gdp = {'Belgium',1;'Bulgaria',2;'Croatia',3};
pop = {'Croatia',30; 'Cyprus', 40; 'Czechia', 50};
gdp = cell2table(gdp,'VariableNames',{'country','gdp'})
gdp =

  3×2 table

     country      gdp
    __________    ___

    'Belgium'      1 
    'Bulgaria'     2 
    'Croatia'      3 

popTable = cell2table(pop,'VariableNames',{'country','pop'})
pop =

  3×2 table

     country     pop
    _________    ___

    'Croatia'    30 
    'Cyprus'     40 
    'Czechia'    50

innerjoin(gdpTable,popTable)
1×3 table

     country     gdp    pop
    _________    ___    ___

    'Croatia'     3     30 

在我看来,您首先要计算所有国家/地区名称列表的交集,然后相应地为元胞数组编制索引。 intersect finds the intersection of two lists, you can call it multiple times in sequence to intersect multiple lists. And ismember 查找所选国家/地区中存在的国家/地区。例如:

A1 = {
'Bulgaria',2
'Croatia',3
'Cyprus',4
'Czechia',5
'Denmark',6
'Estonia',7
};

A2 = {
'Belgium',11
'Bulgaria',12
'Croatia',13
'Cyprus',14
'Denmark',16
'Estonia',17
};

A3 = {
'Belgium',21
'Croatia',23
'Cyprus',24
'Czechia',25
'Denmark',26
'Estonia',27
};

[countries] = intersect(A1(:,1),A2(:,1));
[countries] = intersect(countries,A3(:,1));
i1 = ismember(A1(:,1),countries); A1 = A1(i1,:);
i2 = ismember(A2(:,1),countries); A2 = A2(i2,:);
i3 = ismember(A3(:,1),countries); A3 = A3(i3,:);
A = [A1,A2(:,2),A3(:,2)];

上面的代码假定三个输入元胞数组的国家/地区顺序相同。如果不是这种情况,请使用 sort 对数组进行排序,然后再将它们与所选国家/地区的列表进行匹配:

i1 = ismember(sort(A1(:,1)),countries);