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

6 views (last 30 days)
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

Accepted Answer

Adam
Adam on 28 Jul 2017
Edited: Adam on 28 Jul 2017
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 Comments
Duff Dowdell
Duff Dowdell on 28 Jul 2017
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 on 28 Jul 2017
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!