%% Create Word Cloud from LDA Topic
% To reproduce the results in this example, set rng to 'default'.

rng('default')

% Load the example data. The file sonnetsPreprocessed.txt contains preprocessed versions of Shakespeare's sonnets. The file contains one sonnet per line, with words separated by a space. Extract the text from sonnetsPreprocessed.txt, split the text into documents at newline characters, and then tokenize the documents.

filename = "sonnetsPreprocessed.txt";
str = extractFileText(filename);
textData = split(str,newline);
documents = tokenizedDocument(textData);

% Create a bag-of-words model using bagOfWords.

bag = bagOfWords(documents)

% Fit an LDA model with 20 topics. To suppress verbose output, set 'Verbose' to 0.

mdl = fitlda(bag,20,'Verbose',0)

% Visualize the first four topics using word clouds.

figure
for topicIdx = 1:4
    subplot(2,2,topicIdx)
    wordcloud(mdl,topicIdx);
    title("Topic: " + topicIdx)
end

% Copyright 2012 The MathWorks, Inc.