2014-10-31 62 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