How to access user input strings individually within a 'for' loop

6 次查看(过去 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

采纳的回答

Adam
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 个评论
Duff Dowdell
Duff Dowdell 2017-7-28
That indeed does work, thank you kindly sir. Would this be possible without the use of a cell array by chance? I only ask as cell arrays were not covered up to the point this was assigned. In addition, is it generally more practical to use cell arrays when dealing with user input that is a character type as opposed to numeric(double)?
Adam
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 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