Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting string by number of characters matlab

Is there any builtin function in Matlab that cuts string by the number of characters and returns it as a cell array or something. For example if call A = some_function(string, 3):

Input: string = '1234567890'
Output: A = {'123', '456', '789', '0'}

or do I need to use loops?

Thanks.

like image 541
RobertDeNiro Avatar asked Jan 13 '23 19:01

RobertDeNiro


2 Answers

An alternative solution, which is slightly more elegant (in my opinion), would be using regexp:

A = regexp(str, sprintf('\\w{1,%d}', n), 'match')

where str is your string and n is the number of characters.

Example

>> regexp('1234567890', '\w{1,3}', 'match')

ans = 
    '123'    '456'    '789'    '0' 
like image 68
Eitan T Avatar answered Jan 22 '23 12:01

Eitan T


A little long may be:

ns = numel(string);
n = 3;
A = cellstr(reshape([string repmat(' ',1,ceil(ns/n)*n-ns)],n,[])')'
like image 20
yuk Avatar answered Jan 22 '23 13:01

yuk