我在单元格数组中有许多行,行的末尾有很多额外的空格,如下所示:
'a' 'b' 'c' 'd' [] [] [] [] []
'1' '2' '3' [] [] [] [] [] []
'w' 'x' 'y' 'z' [] [] [] [] []
我想将第二行复制到第一行的末尾,如下:
'a' 'b' 'c' 'd' '1' '2' '3' [] []
'1' '2' '3' [] [] [] [] [] []
'w' 'x' 'y' 'z' [] [] [] [] []
请注意,上面给出的代码是一个任意的例子来说明我想做什么。实际上,我将此功能作为更复杂功能的一个步骤。
我尝试在单元格数组行中搜索第一个空元素,但由于某种原因,isempty不会将它们视为空。是否有人可以指向我的替代方法?
编辑: 完成上述步骤后,第二行将被删除,给出:
'a' 'b' 'c' 'd' '1' '2' '3' [] []
'w' 'x' 'y' 'z' [] [] [] [] []
虽然真正的单元格数组将有比3更多的行。
答案 0 :(得分:5)
我认为这可以满足您的需求。我已将您的单元格数组表示为c
。
n1 = find(cellfun('isempty',c(1,:)), 1); %// first empty cell in row 1
n2 = find(cellfun('isempty',c(2,:)), 1); %// first empty cell in row 2
c(1,n1:n1+n2-2) = c(2,1:n2-1); %// copy the relevant part of row 2 onto row 1
如果第2行中非空单元格的数量超过第1行中的空单元格数,则会自动水平扩展单元格。
示例:输入:
c = {'a' 'b' 'c' 'd' [] [] [] [] []
'1' '2' '3' [] [] [] [] [] []
'w' 'x' 'y' 'z' [] [] [] [] []}
输出:
c =
'a' 'b' 'c' 'd' '1' '2' '3' [] []
'1' '2' '3' [] [] [] [] [] []
'w' 'x' 'y' 'z' [] [] [] [] []
答案 1 :(得分:3)
以下是一种使用高效 logical indexing
来选择非空单元格的一般方法,单cellfun('isempty'
调用并自动扩展,如{{3}中所述} -
C = {
'a' 'b' 'c' 'd' [] [] [] [] []
'1' '2' '3' [] [] [] [] [] []
'w' 'x' 'y' 'z' [] [] [] [] []} %// Input cell array
N = 2; %//Number of rows to process, starting from 2 until the number of rows in C
Ct = C'; %//'# Transpose input cell array, as collecting elements that way is easier
vals = Ct(~cellfun('isempty',Ct(:,1:N))); %//'# elements from selected row(s)
C(1,1:numel(vals)) = vals; %// Place the values into the first row
问题中所述的情况为N = 2
,输出为 -
C =
'a' 'b' 'c' 'd' '1' '2' '3' [] []
'1' '2' '3' [] [] [] [] [] []
'w' 'x' 'y' 'z' [] [] [] [] []
使用N = 3
,您可以复制第一行末尾的第二行和第三行。因此,输出将是 -
C =
'a' 'b' 'c' 'd' '1' '2' '3' 'w' 'x' 'y' 'z'
'1' '2' '3' [] [] [] [] [] [] [] []
'w' 'x' 'y' 'z' [] [] [] [] [] [] []
等等。