在 Matlab 中重复单元格数组列的部分

Repeating parts of a cell array column in Matlab

我在 Matlab 中有一个包含 2 列的元胞数组:

x = {'A', 0
     ' ', 1
     ' ', 1
     'B', 1
     ' ', 0 
     ' ', 1 
     'C', 1
     ' ', 0 
     ' ', 1}

我基本上想编写一个循环来查看第 1 列的所有元素,例如,如果它找到 A,那么接下来的两行 '' 我希望它为它们添加标签A也一样。然后,如果它找到 B,则将接下来的两行替换为 B,然后替换为 C...等等...

我尝试使用 repmat:

for i=1:size(x,1)
      a=repmat({x(i,1),3,1});
end 

我也试过这个:

b = {};
for i = 1:size(x,1)
b = {b repmat(x{i,1}, 3, 2)};
end

但是我没有得到想要的结果。 有人可以帮忙吗?

谢谢

有一种非循环方式可以完成此操作。请注意,以下代码被概括为处理任何长度的标签或 space 的数量(即任何所有 -space 条目都将被先前的标签覆盖):

labelIndex = find(~cellfun(@(s) all(isspace(s)), x(:, 1)));
nRepeats = diff([labelIndex; size(x, 1)+1]);
x(:, 1) = x(repelem(labelIndex, nRepeats), 1)

x =

  9×2 cell array

    'A'    [0]
    'A'    [1]
    'A'    [1]
    'B'    [1]
    'B'    [0]
    'B'    [1]
    'C'    [1]
    'C'    [0]
    'C'    [1]

为了解释以上内容...首先,找到第一列不全是 space 的行的索引(使用 find, cellfun, and isspace). Then, take the differences between these indices (and one past the end of the rows) to get an array of the number of times each label will have to be repeated (using diff). Finally, use repelem 将每个标签复制必要的次数并使用结果作为原始数组行的索引。


注意: repelem 函数直到 MATLAB 版本 R2015a 才引入,因此如果您的版本比该版本更旧,则必须使用以下之一最后一步来自 this question 的解决方案。例如:

% First two lines same as above...
clens = cumsum(nRepeats);
index(clens(end)) = 0;
index([1; clens(1:end-1)+1]) = diff([0; labelIndex]);
x(:, 1) = x(cumsum(index), 1);