[英]how to find the number of repeating strings and their array index in a string array in 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.