フィルターのクリア

Cell array help with strings

2 ビュー (過去 30 日間)
Maddie Long
Maddie Long 2020 年 2 月 18 日
編集済み: Stephen23 2020 年 2 月 19 日
I am trying to write several rows of a cell array into one box of a new cell array.
x = {('Q');('N');('Q');('New');('Q');('N');('Q');}
I need to output a cellarray that has all the Q's and when it reaches 'New' it goes to the next row so the output looks like this:
y = {('Q Q' ; 'Q Q'}
As of right now I have this:
x = {('Q');('N');('Q');('New');('Q');('N');('Q');}
q = string(x);
% T = table()
c = {};
for i = 1:numel(x)
if strcmp(q(i),'Q') || strcmp(q(i),'L')
c = {strjoin(q(i),' ')}
else strcmp(q(i),'New')
end
end
A good point to touch on is that the x array will not be periodic always.

採用された回答

Jacob Wood
Jacob Wood 2020 年 2 月 18 日
One way this could be accomplished is by tracking what cell you are currently looking to write into, and then increasing this "current_cell" every time you see a 'New'. My implementation would look something like:
x = {('Q');('N');('Q');('New');('Q');('N');('Q');};
c = {};
current_cell = 1;
for i = 1:numel(x)
if (strcmp(x{i},'Q') || strcmp(x{i},'L')) && numel(c)<current_cell %meaning this would be the first element in the cell, so we don't need to put a space in front
c{current_cell} = x{i};
elseif strcmp(x{i},'Q') || strcmp(x{i},'L')
c{current_cell} = strjoin({c{current_cell},x{i}}); %strjoin puts the space in for us
elseif strcmp(x{i},'New')
current_cell = current_cell+1;
end
end
  1 件のコメント
Maddie Long
Maddie Long 2020 年 2 月 18 日
You are a literal godsent human. Thank you so much!

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

その他の回答 (1 件)

Stephen23
Stephen23 2020 年 2 月 18 日
編集済み: Stephen23 2020 年 2 月 19 日
>> x = {'Q';'N';'Q';'New';'Q';'N';'Q'};
>> y = 1+cumsum(strcmpi(x,'new'));
>> z = strcmpi(x,'Q') | strcmpi(x,'L');
>> foo = @(v){strjoin(x(v))};
>> out = accumarray(y(z),find(z),[],foo)
out =
'Q Q'
'Q Q'
Or for MATLAB versions before R2013a:
>> baz = @(s)s(2:end);
>> foo = @(v){baz(sprintf(' %s',x{v}))};
>> out = accumarray(y(z),find(z),[],foo)
out =
'Q Q'
'Q Q'

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by