Puzzler for a Monday
显示 更早的评论
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.]
回答(6 个)
Azzi Abdelmalek
2013-7-22
idx=strcmp(A,B)
out=[A(~idx) A(idx)]
Sean de Wolski
2013-7-22
idx = ismember(A,B);
C = cat(isrow(A)+1,A(~idx),A(idx))
1 个评论
Evan
2013-7-22
Awesome. I especially like the "isrow" trick. I'll be remembering that one.
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
2015-1-27
0 个投票
k=ismember(A,B) A(k)='' if sum(k)==0 A=A; else A=[A B] end
David Young
2015-1-27
[~, idx] = ismember(B, A);
C = circshift(A, [0 -idx]);
1 个评论
David Young
2015-1-27
Note: does not preserve the ordering of the other elements.
类别
在 帮助中心 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!