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

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

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

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

我尝试过的事情:

  • 我尝试过str2double来创建允许索引的行。这个 导致NaN值不允许任何操作
  • 我尝试了cell2mat,该错误给出了:数组的维数 级联不一致。
  • 我试图从单元格数组创建表,但是我可以 从不同的单元格数组中粘贴所有数据,因为我 可以减去它

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

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

[~,ib] = intersect(fp(:,lr(:,1));
Com_fplr = [fp(ia,lr(ib,ib] = intersect(Com_popgdp(:,Com_fplr(:,1));
Com_all = [Com_popgdp(ia,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?

有人可以帮助我找到一种方法,将选择单元格数组用作索引以从其他单元格数组中减去数据吗? 哪种方法合适?

beida221 回答:Matlab-如何将一组单元格数组转换为允许索引的数组?

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

首先,将单元格数组更改为表格

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,'gdp'})
gdp =

  3×2 table

     country      gdp
    __________    ___

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

popTable = cell2table(pop,'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找到两个列表的交集,您可以依次多次调用以与多个列表相交。 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(:,countries); A1 = A1(i1,:);
i2 = ismember(A2(:,countries); A2 = A2(i2,:);
i3 = ismember(A3(:,countries); A3 = A3(i3,:);
A = [A1,2),2)];

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

i1 = ismember(sort(A1(:,1)),countries);
本文链接:https://www.f2er.com/3141997.html

大家都在问