MATLAB Answers

How to store string values from a for loop into a cell array?

163 views (last 30 days)
Neil Bhattacharjee
Neil Bhattacharjee on 15 Aug 2016
Edited: Moe_2015 on 15 Aug 2016
Hi. I want the user to input an arbitrary number, and then set up a for loop that asks the question
"Enter a string" as many times as the user indicated above with the first input.
I then want to store all these string values into a cell array, and be able to retrieve these strings later.
How do I do this?
prompt = "Enter a number";
x = input(prompt)
for i=1:x
%Code that asks user to input string
end

  0 Comments

Sign in to comment.

Accepted Answer

Moe_2015
Moe_2015 on 15 Aug 2016
prompt = 'Enter a number: ';
x = input(prompt);
for i=1:x
user_string = input('Enter a string: ');
all_strings{i} = user_string;
end

  3 Comments

Moe_2015
Moe_2015 on 15 Aug 2016
Also, I don't know your end goal but you may want to make this a function to make it cleaner:
function [all_strings] = MyStringFunction()
prompt = 'Enter a number: ';
x = input(prompt);
for i=1:x
user_string = input('Enter a string: ');
all_strings{i} = user_string;
end
Neil Bhattacharjee
Neil Bhattacharjee on 15 Aug 2016
Thanks for the help moe!
I know this might be a little too much, but is there any way I can make it so that I don't have to use quotations when i'm entering strings?
Thanks!
Moe_2015
Moe_2015 on 15 Aug 2016
Yes, replace
user_string = input('Enter a string: ');
with
user_string = input('Enter a string: ','s');
This way you will not need any single quotations and you just have to enter whatever text you want as an input and it will treat it as a string.

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Tags