我非常接近这个问题。我要做的是过滤掉一个单元格数组。单元格数组中可以包含各种项目,但我想要做的是使用递归来拉出字符串。我非常接近这个。当单元格中有空格时,我只会遇到问题。这就是我应该得到的:
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'
答案 0 :(得分: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
答案 1 :(得分:2)
这是一个不同的实现
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
。
答案 2 :(得分:1)
该行
Str = ischar(in{:,:});
是问题所在。它对我没有任何意义。
你接近得到答案,但犯了一些重大但很小的错误。
你需要检查这些东西: 1.循环输入的单元格。 2.对于每个单元格,查看它本身是否为单元格,如果是,请在单元格上调用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