2014-10-31 54 views
0

我在这个问题上非常接近。我必须做的是过滤出一个单元阵列。单元格数组可以包含多种项目,但我想要做的是使用递归来抽出字符串。我非常接近这一个。当单元格中有空格时,我只是有一个问题。这是我应该得到:用递归过滤单元阵列

Test Cases: 

     cA1 = {'This' {{{[1:5] true} {' '}} {'is '} false true} 'an example.'}; 
     [filtered1] = stringFilter(cA1) 
      filtered1 => 'This is an example.' 

     cA2 = {{{{'I told '} 5:25 'her she'} {} [] [] ' knows'} '/take aim and reload'}; 
     [filtered2] = stringFilter(cA2) 
      filtered2 => 'I told her she knows/take aim and reload' 

以下是我有:

%find the strings in the cArr and then concatenate them. 
function [Str] = stringFilter(in) 
Str = []; 
for i = 1:length(in) 
    %The base case is a single cell 
    if length(in) == 1 
     Str = ischar(in{:,:}); 
    %if the length>1 than go through each cell and find the strings. 
     else 
     str = stringFilter(in(1:end-1)); 
     if ischar(in{i}) 
      Str = [Str in{i}]; 
    elseif iscell(in{i}) 
      str1 = stringFilter(in{i}(1:end-1)); 
      Str = [Str str1]; 

     end 
    end 

end 

end 

我试图用“ismember”,但没有奏效。有什么建议么?我的代码输出以下:

 filtered1 => 'This an example.' 
     filtered2 => '/take aim and reload' 

回答

2

您可以相当简化功能

function [Str] = stringFilter(in) 
Str = []; 
for i = 1:length(in) 
    if ischar(in{i}) 
     Str = [Str in{i}]; 
    elseif iscell(in{i}) 
     str1 = stringFilter(in{i}); 
     Str = [Str str1]; 
    end 
end 

end 

只是遍历单元中的所有元素测试,无论是字符串或细胞。在后者中,再次调用该单元格的函数。输出:

>> [filtered1] = stringFilter(cA1) 

filtered1 = 

This is an example. 

>> [filtered2] = stringFilter(cA2) 

filtered2 = 

I told her she knows/take aim and reload 
+0

这个好工作! – Divakar 2014-10-31 14:51:09

+0

好吧,这真的有道理:)谢谢! – 2014-10-31 16:06:26

1

线

Str = ischar(in{:,:}); 

就是问题所在。这对我没有任何意义。

你很接近获得答案,但犯了一些重大但小错误。

您需要检查以下事项: 1.循环输入的单元格。 2.对于每个单元格,查看它本身是否为单元格,如果是,请在单元格的VALUE上调用stringFilter 3.如果它不是单元格,而是字符数组,则按原样使用其VALUE。 4.否则,如果单元格VALUE包含非字符,该单元格对输出的贡献是''(空白)

我认为您犯了一个错误,未利用in(1)和在{1}。 无论如何,这是我的版本的功能。有用。

function [out] = stringFilter(in) 
out = []; 

for idx = 1:numel(in) 
    if iscell (in{idx}) 
     % Contents of the cell is another cell array 
     tempOut = stringFilter(in{idx}); 
    elseif ischar(in{idx}) 
     % Contents are characters 
     tempOut = in{idx}; 
    else 
     % Contents are not characters 
     tempOut = ''; 
    end 

    % Concatenate the current output to the overall output 
    out = [out, tempOut]; 
end 

end 
+0

这也是有道理的,谢谢:) – 2014-10-31 16:06:44

2

这是一个不同的implememntation

function str = stringFilter(in) 
if ischar(in) 
    str = in; 
elseif iscell(in) && ~isempty(in) 
    str = cell2mat(cellfun(@stringFilter, in(:)', 'uni', 0)); 
else 
    str = ''; 
end 
end 

如果它是字符串,返回。如果是单元格,则在所有元素上应用相同的函数并连接它们。在这里,我使用in(:)'来确保它是一个行向量,然后cell2mat连接结果字符串。如果该类型是其他任何内容,则返回一个空字符串。我们需要检查单元阵列是否为空,因为cell2mat({})的类型为double

+0

我明白,但cell2mat通常是皱眉,因为我们没有教会使用它 – 2014-10-31 16:07:09