【问题标题】:using ismember for numeric values将 ismember 用于数值
【发布时间】:2014-05-16 13:13:21
【问题描述】:

我有一个双精度类型的 4554 x 1 向量,称为 company_info,ind_vec。我还有另一个 25 x 1 向量,它是称为 groups.industy_labels 的单元格数组类型。

groups.industy_labels 包含一个数字代码列表。 company_info,ind_vec 包含相同的数字代码。

我计划执行以下操作,其中我使用 ismember 返回 groups.industy_labels 中每个数字代码的索引,然后对与 company_info,ind_vec 相关的另一个向量求和,即另一个 4554 x 1 向量。

[~, index_sub]              = ismember(company_info.ind_vec, groups.industy_labels);
groups.industy_exps(:, 1)   = accumarray(index_sub, pwgt , [], @sum, 0);

但是 Matlab 告诉我 ismember 只接受字符串的单元格数组。还有其他方法吗?

【问题讨论】:

  • 先尝试将该元胞数组转换为双精度数组? - ismember(company_info.ind_vec, cell2mat(groups.industy_labels))

标签: matlab


【解决方案1】:

实际上,错误消息有点欺骗性,因为您可以ismember 用于数值:

x=[1 3]
y=[1 2]   
ismember(x,y) %This will work

您也可以将它用于元胞数组,但仅限于字符串:

x=[{'a'},{'c'}]
y=[{'a'},{'b'}]
ismember(x,y) %This will work

x=[{1},{3}]
y=[{1},{2}]
ismember(x,y) %This will fail

因此,在您的情况下,您可能希望在 2 个数字向量上使用它,而不是 1 个数字向量和 1 个元胞数组:

x=[1,2] %Numeric vector
y=[{1},{2}] %Cell array

y_numeric = [y{:}] %Made into a numeric vector

ismember(x,y_numeric) %This will work

请注意,这假定元胞数组中的每个条目仅包含一个数字。

【讨论】:

    猜你喜欢
    • 2018-11-22
    • 2013-03-29
    • 2013-01-27
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    相关资源
    最近更新 更多