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

6 ビュー (過去 30 日間)
Duff Dowdell
Duff Dowdell 2017 年 7 月 28 日
コメント済み: Adam 2017 年 7 月 28 日
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 Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by