Create three cell array variables that store people’s name, verbs, and nouns

Create three cell array variables that store people’s name, verbs, and nouns.
For example,
names = {‘Harry’, ‘Xavier’, ‘Sue’};
verbs {‘loves’, ‘eats’);
nouns {‘baseballs’, ‘rocks’, ‘sushi’};
Write a script that will initialze these cell array, and then print sentences using one random element from each cell array (e.g., “Xavier eats sushi’)

The Correct Answer and Explanation is :

Certainly! Below is a MATLAB script that initializes three cell arrays containing names, verbs, and nouns. It then selects one random element from each array to form and print a sentence.

% Initialize the cell arrays
names = {'Harry', 'Xavier', 'Sue'};
verbs = {'loves', 'eats'};
nouns = {'baseballs', 'rocks', 'sushi'};

% Generate random indices for each cell array
nameIndex = randi(numel(names));
verbIndex = randi(numel(verbs));
nounIndex = randi(numel(nouns));

% Select random elements from each cell array
randomName = names{nameIndex};
randomVerb = verbs{verbIndex};
randomNoun = nouns{nounIndex};

% Form and print the sentence
sentence = sprintf('%s %s %s.', randomName, randomVerb, randomNoun);
disp(sentence);

Explanation

Here’s a step-by-step breakdown of what the script does:

  1. Initialize Cell Arrays: The script begins by defining three cell arrays: names, verbs, and nouns. Each array is initialized with a set of strings. In MATLAB, cell arrays are used to store elements of different types or sizes. In this case, each cell contains a string.
  2. Generate Random Indices: The script uses the randi function to generate a random index for each array. The randi function requires the maximum value as an argument, which we provide using the numel function. numel returns the number of elements in the array, ensuring that the random index is within valid bounds.
  3. Select Random Elements: With the indices determined, the script retrieves an element from each array based on these indices. The elements are stored in randomName, randomVerb, and randomNoun, respectively.
  4. Create and Display Sentence: Using the sprintf function, the script constructs a sentence by combining the randomly selected elements with appropriate spaces and punctuation. The sentence is then displayed using the disp function.

This script efficiently combines elements of language to dynamically create simple sentences, demonstrating the use of arrays, random number generation, and string manipulation in MATLAB.

Scroll to Top