Write a function that will receive a character and a positive integer n. It will create and return a cell array with strings of increasing lengths, from 1 to the integer n. It will build the strings with successive characters
이전 댓글 표시
Write a function buildstr that will receive a character and a positive integer n. It will create and return a cell array with strings of increasing lengths, from 1 to the integer n. It will build the strings with successive characters in the ASCII encoding. >> buildstr('a',4) ans = 'a' 'ab' 'abc' 'abcd'
댓글 수: 1
Stephen23
2017년 9월 27일
@Raman Sah: what have you tried so far?
답변 (2개)
Eeshan Mitra
2017년 9월 29일
You could use the MATLAB functions "double" and "char" for this purpose.
Assuming you have already gotten the function to read the inputs, lets say buildstr('a',3), then for the character 'a':
>> double('a')
ans =
97
would yield the ASCII code for the character. You can write your logic and subsequently use the function "char" to convert an ASCII code back to a character. For example:
>> char(double('b') + 1)
ans =
'c'
Of course in your case, you will need to compensate for edge-cases, like what would you expect when you enter:
buildstr('y',5)
Akira Agata
2017년 9월 29일
The function becomes like this. Please note that the following sample script is very basic one. So, some exception handling process should be added for practical use.
function output = buildstr(str, num)
list = 'abcdefghijklmnopqrstuvwxyz';
idx = strfind(list,str);
output = arrayfun(@(x) list(idx:idx+x-1), [1:num],'UniformOutput',false);
end
댓글 수: 4
Simpler, and without the risk of missing characters:
list = 'a':'z';
Also note that the square brackets are not required, and are highlighted as such by the MATLAB editor:

Raman Sah
2017년 10월 1일
Stephen23
2017년 10월 1일
@Raman Sah: of course you can do this without arrayfun. Anything that can be done with arrayfun or cellfun can also be done with a loop.
Akira Agata
2017년 10월 2일
Hi Stephen-san,
Thank you for brushing up my post! :-)
카테고리
도움말 센터 및 File Exchange에서 String에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!