簡體   English   中英

Matlab:如何使用特定索引的字符串構建數組

[英]Matlab: How to build array with strings at specific index

我有一個單元格字符串數組(長度= 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中完成?

這是另一種方法,與上面的方法非常相似,但是沒有repmat

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

我已替換了傳統的@isempty因為它可能會更快 感謝@LuisMendo在評論中提及。

一種可能的方法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM