How to access user input strings individually within a 'for' loop
조회 수: 7 (최근 30일)
이전 댓글 표시
I am attempting to write a code that will allow me to ask user for number of input strings they will enter, and then use a 'for' loop to allow input of strings. I am having difficulty with accessing each individual string, as they are overwritten on each iteration. Is there any advice on what the best approach is to this issue? Included is what I've generated thus far:
x = input('Enter number of strings you will input: ');
if (x<=0) disp('Invalid entry'); end
my_str = zeros(length(x));
for ii=1:x
my_str = input('Enter string: ', 's');
end
댓글 수: 0
채택된 답변
Adam
2017년 7월 28일
편집: Adam
2017년 7월 28일
my_str = cell(1,x);
for ii=1:x
my_str{ii} = input('Enter string: ', 's');
end
Probably the pre-allocation is not necessary with a cell array, but I rarely use them so haven't really tested it.
zeros(length(x));
is wrong on any number of counts!
zeros(n)
creates an n*n numeric array and length(x) will give you the length (longest dimension) of x, not its value. In this case that will be 1 as it is a scalar so you will just end up with a scalar 0.
But the main part you were missing was to index into an array (one that is not created as numeric) in the loop.
댓글 수: 2
Adam
2017년 7월 28일
Strings have different length so you cannot store them in a regular array as chars. The current (and very recent) version of Matlab has a string type which, as far as I know, you can create an array of, which doesn't have the constraint that all elements of the array must be the same length, though I haven't use these strings much yet myself so I'm not entirely sure about all their functionality. I imagine if cell arrays haven't been covered yet though then string arrays also haven't.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!