How to access user input strings individually within a 'for' loop
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
Adam
am 28 Jul. 2017
Bearbeitet: Adam
am 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 Kommentare
Adam
am 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!