Given a cell array of strings
A = {'MATLAB','HURRAY','SPARKLY','KITTENS','FUN'};
and a particular string value
B = 'KITTENS';
ensure that B is the last element of the cell array. If it isn't, move it to the end of A.
You cannot assume that B appears at all (in which case return A unchanged), but you can assume B does not appear more than once.
[I have a solution, but I post this as a puzzle because I bet someone can find a slicker one.]

Antworten (6)

Azzi Abdelmalek
Azzi Abdelmalek am 22 Jul. 2013

2 Stimmen

idx=strcmp(A,B)
out=[A(~idx) A(idx)]
the cyclist
the cyclist am 22 Jul. 2013

2 Stimmen

Here's mine:
[~,idx] = sort(ismember(A,B));
A = A(idx)
Sean de Wolski
Sean de Wolski am 22 Jul. 2013

1 Stimme

idx = ismember(A,B);
C = cat(isrow(A)+1,A(~idx),A(idx))

1 Kommentar

Evan
Evan am 22 Jul. 2013
Awesome. I especially like the "isrow" trick. I'll be remembering that one.

Melden Sie sich an, um zu kommentieren.

Evan
Evan am 22 Jul. 2013
Bearbeitet: Evan am 22 Jul. 2013

0 Stimmen

Here's my solution. It's ugly, but I think it's fairly general. :P
function A = cell_shuffle(A)
idx = cellfun(@(x)isequal(B,x),A);
A = [A(~idx) A(idx)];
end
This would make for a nice CODY problem, by the way.
Abdullah Caliskan
Abdullah Caliskan am 27 Jan. 2015

0 Stimmen

k=ismember(A,B) A(k)='' if sum(k)==0 A=A; else A=[A B] end
David Young
David Young am 27 Jan. 2015

0 Stimmen

[~, idx] = ismember(B, A);
C = circshift(A, [0 -idx]);

1 Kommentar

David Young
David Young am 27 Jan. 2015
Note: does not preserve the ordering of the other elements.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Startup and Shutdown finden Sie in Hilfe-Center und File Exchange

Produkte

Gefragt:

am 22 Jul. 2013

Kommentiert:

am 27 Jan. 2015

Community Treasure Hunt

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

Start Hunting!

Translated by