How do I get a character array to return a sentence stored in a single row character vector?
2 次查看(过去 30 天)
显示 更早的评论
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)
0 个评论
回答(2 个)
Angelo Yeo
2023-7-4
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'.
0 个评论
Aditya Singh
2023-7-4
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!