converting cells with strings inside cells into strings inside cells

I use the following code: cellfun(@(x) regexp(x, '@(.*)@', 'tokens'), array_of_strings) The idea is to replace all the strings in the array with only the substring between the @'s. It works, the only problem is that the 'tokens' option leaves me with cells inside cells, which is inconvenient. My questions are: 1. Is there an alternative way to do it without getting cells inside cells? 2. It is interesting for me to know if there is a function that converts "cell arrays with strings inside a cell array" into simply "strings in a cell array". Thanks

2 件のコメント

Paolo
Paolo 2018 年 7 月 24 日
Can you show a sample of array_of_strings?
Micha
Micha 2018 年 7 月 24 日
array_of_strings = {'a @one@', 'a @two@', 'a@three@'};

サインインしてコメントする。

 採用された回答

Paolo
Paolo 2018 年 7 月 24 日
編集済み: Paolo 2018 年 7 月 24 日

1 投票

cellfun(@(x) regexp(x,'(?<=@)(.*)(?=@)','match'),array_of_strings)
Or
cellfun(@(x) regexp(x,'(?<=@)(.*)(?=@)','tokens','once'),array_of_strings)

6 件のコメント

Micha
Micha 2018 年 7 月 24 日
This is a nice solution. Thank you.
Also I would be happy to know if there is an answer for question 2.
Paolo
Paolo 2018 年 7 月 24 日
You are welcome. Not sure I follow the second question, do you mean going from:
nested = {{'one','two'}}
To
unnested = nested{:}
?
Micha
Micha 2018 年 7 月 24 日
I'm sorry, now I realized my original code didn't reproduce what I meant for question 2.
The cellfun was supposed to be with UniformOutput set to false:
array_of_strings = {'a @one@', 'a zero', 'a @two@', 'a @three@'};
% now we have to set it to false because one cell is going to become empty.
new_array = cellfun(@(x) regexp(x, '@(.*)@', 'tokens'), array_of_strings, 'UniformOutput', false);
% remove the empty cells
new_array = new_array(~cellfun('isempty', new_array))
What I get now is: 1×3 cell array
{1×1 cell} {1×1 cell} {1×1 cell}
Now I don't want these to be cells inside a cell array, but rather just strings as before.
Micha
Micha 2018 年 7 月 24 日
Of course, your 2 solutions solved this problem to begin with. But I was interested if there is any function to "fix" this new condition.
Paolo
Paolo 2018 年 7 月 24 日
>>horzcat(new_array{:})
{'one'} {'two'} {'three'}
Does this help?
Micha
Micha 2018 年 7 月 24 日
編集済み: Micha 2018 年 7 月 24 日
That seems to do the trick
Thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

製品

リリース

R2017b

タグ

質問済み:

2018 年 7 月 24 日

編集済み:

2018 年 7 月 24 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by