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

2 vues (au cours des 30 derniers jours)
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)

Réponses (2)

Angelo Yeo
Angelo Yeo le 4 Juil 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 le 4 Juil 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

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by