2014-10-31 89 views
0

建立与字符串数组我有字符串的单元阵列(长度= 4):
A = {'a', 'b', 'c', 'd'}
我有索引的双矩阵(长度= 4):
B = [2, 4, 6, 8]Matlab的:如何在特定索引

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

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

这怎么能在Matlab做?

+0

你是怎么和8一起来的?它是'4 + 4',还是'B'中的最大索引? – 2014-10-31 01:04:09

+0

不,A','B'和'C'的长度是任意的,除了'A'和'B'的长度需要相等(因为'B'中的索引对应于'A')。 – Todd 2014-10-31 01:12:32

+0

我的意思是,如果B是'B = [100 200 300 400]'? – 2014-10-31 01:13:04

回答

1

一个可行的方法:

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 ' ' 

最后一行可以简化如下(不repmat需要),作为注意到@ ParagS.Chandakkar:

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

太好了,谢谢!我只会在你的代码之前添加这一步,以创建空单元格数组''C = repmat({''},1,8);' – Todd 2014-10-31 01:11:40

2

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

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

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

+0

+1发现了!实际上不需要'repmat' – 2014-10-31 01:20:24

+1

'C(cellfun('isempty',C))'可能比C更快[http://undocumentedmatlab.com/blog/cellfun-undocumented-performance-boost] (@的isEmpty,C))' – 2014-10-31 01:22:28