2014-10-31 50 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