필터 지우기
필터 지우기

create and display a cell array that have a same length of requiremant

조회 수: 1 (최근 30일)
jarvan
jarvan 2014년 11월 17일
댓글: jarvan 2014년 11월 18일
I a writting a script that will create and display a cell array that will loop to store strings of lengths 4, 5, 6, and 7. it will ask the user for the string and also make a error-check. for example:
Enter a string of length 5: hello
Enter a string of length 6: !@#$%^
ncell{2} =
hello
Error: String has wrong length
ncell{3} =
!@#$%^
Here is my code
stringlength = cell(4,1);
n = 4;
for i = n:7
stringlength{i} = input('Enter a string of length :','s')
if length(stringlength) ~= i
disp('Enter the right one')
else
stringlength{i} = input('Enter a string of length :','s')
end
end
However, the code seems wrong because it keeps going although I put in a wrong length of strings

채택된 답변

Guillaume
Guillaume 2014년 11월 17일
length(stringlength) is the length of the cell array, so it's 4. So your
if length(stringlength) ~= i
will always be true on the first iteration of the loop ( i = 4) and false all the others ( i=5:7).
You forgot to index in the cell array. To test the length of the string:
length(stringlength{i})
Note that there's a flaw in your program. If the user fails to enter a string of the right size, you ask him again to enter a string of the right size. The second time round, you don't check it, so any size can be entered.
  댓글 수: 1
jarvan
jarvan 2014년 11월 18일
thank your for warning me that adding the error-check with the right size.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by