Why my program doesn't work?

2 views (last 30 days)
Isaac Ng
Isaac Ng on 10 Oct 2015
Commented: Star Strider on 10 Oct 2015
names = {'Harry', 'Xavier', 'Sue'};
verbs = {'loves', 'eats'};
nouns = {'baseballs', 'rocks', 'sushi'};
a = names(randi(length(names)));
v = verbs(randi(length(verbs)));
o = nouns(randi(length(nouns)));
fprintf {'%s %s %s \n', a, v, o}
I can't print out the words. I keep getting the error "Error using fprintf. Function is not defined for 'cell' inputs."
  1 Comment
James Tursa
James Tursa on 10 Oct 2015
What are you trying to do? Print out some random combinations of the above? All of the possible combinations? Or what?

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 10 Oct 2015
Change your fprintf call to:
fprintf('%s %s %s \n', char(a), char(v), char(o))
  2 Comments
Durgesh Naik
Durgesh Naik on 10 Oct 2015
please go through struct once........!
Star Strider
Star Strider on 10 Oct 2015
@Durgesh — I don’t understand what you mean by ‘struct’. There are no structure variables involved in the code.
As for the line itself, ‘a’ and the others are cells, so you have to use char to print them with fprintf. Since printing them is the problem, my code solves it.
The rest of the code in the original post works correctly, and does not need to be modified.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 10 Oct 2015
Wrong braces and parentheses. See the FAQ for a good explanation of when to use braces and when to use parentheses. http://matlab.wikia.com/wiki/FAQ#What_is_a_cell_array.3F
Here is the corrected code:
rng('shuffle'); % Randomize the seed.
names = {'Harry', 'Xavier', 'Sue'};
verbs = {'loves', 'eats'};
nouns = {'baseballs', 'rocks', 'sushi'};
a = names{randi(length(names))};
v = verbs{randi(length(verbs))};
o = nouns{randi(length(nouns))};
fprintf('%s %s %s \n', a, v, o);

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!