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 CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by