Scramble words in MATLAB.

hi my friends. im looking for if there is any way to scramble word in MATLAb. exactly i want that a function returns a string containing the words in the original string in random order and also i wannaa use randperm to do tthat. i wrote this function but i was not succesful.
function [sout] = scrambleWords(s)
%for Non-Functional use%
%s = input('Enter a few Words:\n','s');
cutPoints = regexp(s,'\s{1,}'); % for More than 1 Space=> '\s{2,}'
sout = mat2cell(s,1,diff([0 cutPoints numel(s)]));
sout = randperm(sout,10,3);
end

Answers (3)

Mischa Kim
Mischa Kim on 14 Jan 2014
Edited: Mischa Kim on 14 Jan 2014
See below:
function [permsout] = scrambleWords(s)
cutPoints = regexp(s,'\s{1,}'); % for More than 1 Space=> '\s{2,}'
sout = mat2cell(s,1,diff([0 cutPoints numel(s)]));
perm = randperm(length(sout));
permsout = sout(perm);
end
As a last step you could convert the cell array back to a string and return by the function.
Hi Mr Kim. i tried ur code but it does not get in random order. it was the result:
>> scrambleWords('String to Randperm')
sout =
'String ' 'to ' 'Randperm'
perm =
1 2 3
permsout =
'String ' 'to ' 'Randperm'
ans =
'String ' 'to ' 'Randperm'
>>

1 Comment

Mischa Kim
Mischa Kim on 14 Jan 2014
Edited: Mischa Kim on 14 Jan 2014
You are probably still working with some old code. Copy and paste the function in my answer and save under a new function name. This is what I get:
>> scrambleWords('this should really work')
ans =
'work' 'should ' 'this ' 'really '
>> scrambleWords('this should really work')
ans =
'should ' 'really ' 'this ' 'work'
>> scrambleWords('this should really work')
ans =
'should ' 'this ' 'really ' 'work'

Sign in to comment.

ADiNoS
ADiNoS on 14 Jan 2014
Edited: ADiNoS on 14 Jan 2014

0 votes

thank u. now it works like charm.

Categories

Find more on Particle & Nuclear Physics in Help Center and File Exchange

Tags

Asked:

on 14 Jan 2014

Edited:

on 14 Jan 2014

Community Treasure Hunt

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

Start Hunting!