필터 지우기
필터 지우기

how to add and sort a cell with a string in a cell array in order to replace or add a cell with respect the last word of the cell?

조회 수: 3 (최근 30일)
I did this using a lot of lines and I was wondering if you could recommend me a better way to do it.
I have a predefined cell array and I'm constantly generating new data that I have to add or replace in the cell array and sorted regarding the last word of the cell.
Let's say I have a cell array A like:
A{1, 1} = 'whatever - a';
A{2, 1} = 'doesNotMatter - b';
A{3, 1} = 'not even with spaces - d';
A{4, 1} = 'blablabla - ee';
if I have these new cells to add in my array
newCell1 = 'thanksForHelping - c';
newCell2 = 'I really appreciate it - ee';
I would like to add newCell1 (since "c" is not in the original) and replace newCell2 with the one in A{4, 1} (since "ee" is there)
so at the end, I can obtain something like:
A =
5×1 cell array
'whatever - a'
'doesNotMatter - b'
'thanksForHelping - c'
'not even with spaces - d'
'I really appreciate it - ee'
I know that the ideal thing will be to change the data to "a - whatever" and use a simple sort but it is not possible to change the final format.
Could you recommend me something?
Thanks!

채택된 답변

the cyclist
the cyclist 2018년 1월 22일
% The data
A{1, 1} = 'whatever - a';
A{2, 1} = 'doesNotMatter - b';
A{3, 1} = 'not even with spaces - d';
A{4, 1} = 'blablabla - ee';
newCell{1,1} = 'thanksForHelping - c';
newCell{2,1} = 'I really appreciate it - ee';
% Find last words in the old and new data
hyphenIndexA = regexp(A,'-');
lastWordA = cellfun(@(x,y)x(y+2:end),A,hyphenIndexA,'UniformOutput',false);
hyphenIndexNew = regexp(newCell,'-');
lastWordNew = cellfun(@(x,y)x(y+2:end),newCell,hyphenIndexNew,'UniformOutput',false);
% Swap in the replacements if they exist
[tfReplace,locationIndexReplace] = ismember(lastWordA,lastWordNew);
A(tfReplace) = newCell(locationIndexReplace(tfReplace));
% Append the new to the old, if they do not exist
[tfAdd,locationIndexAdd] = ismember(lastWordNew,lastWordA);
A = [A; newCell(not(tfAdd))]
  댓글 수: 3
the cyclist
the cyclist 2018년 1월 22일
편집: the cyclist 2018년 1월 22일
Be sure to do that step after you've got the new elements and replacements in there.
There might be a more efficient way to combine some of those steps, I suppose. But better to understand the whole algorithm first.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by