【问题标题】:Matlab: How to build array with strings at specific indexMatlab:如何使用特定索引处的字符串构建数组
【发布时间】:2014-10-31 00:56:00
【问题描述】:

我有一个字符串元胞数组(长度 = 4):
A = {'a', 'b', 'c', 'd'}
我有一个双索引矩阵(长度 = 4):
B = [2, 4, 6, 8]

如何创建length = 8 的新元胞数组C(字符串),它使用B 中的索引将A 中的字符串放入新数组C。对于B 中未指定的任何索引,我想输入一个' ' 空格(空字符串)。注意:我的真实数据不会“每隔一个”。

C = {' ', 'a', ' ', 'b', ' ', 'c', ' ', 'd'}

如何在 Matlab 中做到这一点?

【问题讨论】:

  • 你是怎么来的 8?是4+4,还是B中的最大索引?
  • 不,ABC 的长度是任意的,除了 AB 的长度需要相等(因为 @ 中的索引987654338@对应A中的字符串)。
  • 我的意思是,如果 B 是 B=[100 200 300 400]
  • 是的,B 的值可以是 [100, 200, 300, 400],但是我的新元胞数组 C 至少需要长度 = 400 或更大。

标签: arrays matlab


【解决方案1】:

这是另一种方法,与上述非常相似,但没有repmat

C(B)=A;
C(cellfun('isempty',C))={' '}; 

我已经替换了传统的@isempty,因为它可能是faster。感谢@LuisMendo 在评论中提到这一点。

【讨论】:

  • C(cellfun('isempty',C)) 可能是 faster 而不是 C(cellfun(@isempty,C))
【解决方案2】:

一种可能的方法:

C = repmat({' '}, 1, max(B)); %// predefine with ' ';
C(B) = A; %// replace actual values

或者:

C(B) = A; %// this automatically fills missing values with [] 
ind = cellfun('isempty', C); %// find occurrences of [] 
C(ind) = repmat({' '}, 1, sum(ind)); %// replace them with ' '

如@ParagS.Chandakkar 所述,最后一行可以简化如下(不需要repmat):

C(ind) = {' '}; %// replace them with ' '

【讨论】:

  • 太好了,谢谢!我只会在您的代码之前添加此步骤,以创建空单元格数组C = repmat({''},1,8);
猜你喜欢
  • 2012-01-20
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-20
  • 1970-01-01
相关资源
最近更新 更多