having problem with sttrep function and empty matrix..

1 回表示 (過去 30 日間)
hyunmin
hyunmin 2014 年 2 月 18 日
コメント済み: Jos (10584) 2014 年 2 月 18 日
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..

回答 (1 件)

Jos (10584)
Jos (10584) 2014 年 2 月 18 日
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 件のコメント
Jos (10584)
Jos (10584) 2014 年 2 月 18 日
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)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by