having problem with sttrep function and empty matrix..
1 view (last 30 days)
Show older comments
I want to make the results like this:
>>phraseblanks
phrasemat = Hello and how are you?
Hi there everyone!
How is it going?
WHazzup?
Phrase 1 had 4 blanks
Phrase 2 had 3 blanks
Phrase 3 had 2 blanks
Phrase 4 had 0 blanks
New phrasemat is :
Hello&and&how&are&you?
Hi&there&everyone!
How&is&it&going?
WHazzup?
----------------------------------- so I made script
"phraseblanks.m"
phrasemat = char('Hello and how are you?', ... 'Hi there everyone!', 'How is it going?', 'WHazzup?')
[r, c] = size(phrasemat);
for i = 1:r
phrasemat_new = cell(r,c);
howmany = countblanks(phrasemat(i,:));
fprintf('Phrase %d had %d blanks\n',i,howmany);
phrasemat(j,:)=strrep(phrasemat(i,:),' ','&')
phrasemat_new{i,:} = [phrasemat(i,:)];
end
fprintf('Changing one is %s\n',eval('phrasemat_new'));
-------------------------- script "countblanks.m"
function num = countblanks(phrase)
% countblanks returns the # of blanks in a trimmed string
% Format: countblanks(string)
num = length(strfind(strtrim(phrase), ' '));
end -----------------------------------
and I keep having errors.
please help me..
0 Comments
Answers (1)
Jos (10584)
on 18 Feb 2014
You are better off storing the phrases in a cell array of chars, as these phrases can have different lengths.
phrasemat = {'Hello and how are you?', 'Hi there everyone!', 'How is it going?', 'WHazzup?'}
Now you can define a function that operates on a string and counts the number of spaces.
CountSpaces = @(str) sum(str==' ') ;
Countspaces('Hello world, my name is Hyunmin!') % will return 5
which you can easily apply to all sentences in your cell array using CELLFUN:
Nspaces = cellfun(CountSpaces, phrasemat)
1 Comment
Jos (10584)
on 18 Feb 2014
And if you want to replace the spaces with something else, create a new function
ReplaceSpacesFunction = @(str) strrep(str, ' ', '#')
NewPhrases = cellfun(ReplaceSpacesFunction, phrasemat, 'UniformOutput', false)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!