简体   繁体   English

Matlab:如何使用特定索引的字符串构建数组

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

I have a cell array of strings (length = 4): 我有一个单元格字符串数组(长度= 4):
A = {'a', 'b', 'c', 'd'}
I have a double matrix of indices (length = 4): 我有一个索引的双重矩阵(长度= 4):
B = [2, 4, 6, 8]

How can I create a new cell array C (of strings) of length = 8 , that uses the indices in B to place the strings from A into the new array C . 我如何创建一个新的length = 8 (字符串)单元格数组C ,它使用B的索引将字符串从A放置到新数组C For any index not specified in B , I want to enter a ' ' space (empty string). 对于B未指定的任何索引,我想输入一个' '空间(空字符串)。 Note: my real data does not go "every-other". 注意:我的真实数据不会“彼此”。

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

How can this be done in Matlab? 如何在Matlab中完成?

This is another approach, very similar to the above, but no repmat . 这是另一种方法,与上面的方法非常相似,但是没有repmat

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

I have replaced traditional @isempty since it may be faster . 我已替换了传统的@isempty因为它可能会更快 Thanks @LuisMendo for mentioning that in a comment. 感谢@LuisMendo在评论中提及。

One possible approach: 一种可能的方法:

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

Or: 要么:

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

The last line could be simplified as follows (no repmat needed), as noted by @ParagS.Chandakkar: 如@ ParagS.Chandakkar所述,可以将最后一行简化如下(不需要repmat ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM