필터 지우기
필터 지우기

countdown the received character

조회 수: 1 (최근 30일)
jarvan
jarvan 2014년 11월 17일
댓글: Star Strider 2014년 11월 18일
Hi guys, I have a function which will accept the characters and n, this function is a cell array with strings of decreasing lengths, from the integer n to 1. For example, when I type buildstr('a',4), the answer should be 'abcd' 'abc' 'ab' 'a'. However the code below doesnt satisfy my requirement. Can someone point out the error code?
function str=buildstr(ch,n)
temp='';
if(n<0)
str='';
else
str=cell(n,1);
for i=n:1
if(i==1)
str(i)={char(ch)};
else
temp=char(str(i+1));
str(i)={strcat(temp,char(ch))};
end
end
end

채택된 답변

Star Strider
Star Strider 2014년 11월 17일
You’re almost there.
if(n<0)
str='';
else
str=cell(n,1);
for i=n:-1:1
if(i==n)
str{i}=char(ch);
else
temp=char(str{i+1}+1);
str{i}=strcat(char(ch),temp);
end
end
end
There were three problems:
  1. Your loop wasn’t iterating because in MATLAB, for loops by default count upward, so if the terminal value is less than the initial value, the loop is satisfied and never iterates. You need to decrement it by telling it to count down, specifying the interval to (in this instance) to be -1;
  2. Your ‘temp’ variable subscript needs to ‘look back’ (which is to say to add 1 to ‘i’) at every iteration, and add 1 to the previous value of ‘str’;
  3. Your strcat arguments were reversed.
A minor observation: it’s best to not use ‘i’ or ‘j’ as loop counters. They are the imaginary operators in MATLAB.
  댓글 수: 2
jarvan
jarvan 2014년 11월 18일
i=n:-1:1 is all I need in the code, I was frustrating in counting down with for-loop. thanks for sharing your information
Star Strider
Star Strider 2014년 11월 18일
My pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by