How do I get a character array to return a sentence stored in a single row character vector?

2 views (last 30 days)
I am trying to get a character array of "sentence = 'Hello, how are you doing?'." I also am supposed to get an output for a hidden set of words and I have no idea how to go about that. Any help would be appreciated.
function sentence = sentenceMaker(words)
%[sentence] = sentenceMaker(words)
% This function accepts a cell array of words and concatenates them in a
% single character array to define a sentence
[NumberWords, ~] = size( ); % Write missing code
sentence = ; % Write missing code
for ndx = 2: % Write missing code
sentence = [sentence ' ' ]; % Write missing code
end
% Code to call your function (given):
words = {'Hello,' ; 'how'; 'are'; 'you'; 'doing?'}
sentence = sentenceMaker(words)

Answers (2)

Angelo Yeo
Angelo Yeo on 4 Jul 2023
Hint)
1) The function size returns the size of matrices. E.g., if A = rand(5, 4), then size(A) is equal to [5, 4].
2) An empty vector can be represented as [].
3) To concatenate characters you can put the characters into the square brackets [ ]. E.g., ['Hi, ' ', 'Hello'] becomes 'Hi Hello'.

Aditya Singh
Aditya Singh on 4 Jul 2023
Hi Serena,
You need to iterate over the words and then concatnate to the character array.
function sentence = sentenceMaker(words)
%[sentence] = sentenceMaker(words)
% This function accepts a cell array of words and concatenates them in a
% single character array to define a sentence
[NumberWords, ~] = size(words); % Calculate the number of words
sentence = words{1}; % Initialize the sentence with the first word
for ndx = 2:NumberWords % Loop through the remaining words
sentence = [sentence ' ' words{ndx}]; % Concatenate each word with a space
end
You can also use strjoin function of MATLAB, to give a one line solution.
For more information please refer to
Hope it helps

Products

Community Treasure Hunt

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

Start Hunting!