mia saam
mia saam

Reputation: 5

divide char array into N equal parts matlab

I have a char array, for example:

a = '123456abced5421f'

and I want to divide it into equal parts (e.g: b(1) = '123456ab' and b(2) = 'ced5421f') so when I call b(1) it will return 8 elements not just 1 element.

How can I do this in Matlab?

I tried using cell array and reshape, the cell array will increase the size of the array so I don't want to use it, and the reshape will return only 1 element.

Upvotes: 0

Views: 1258

Answers (2)

EBH
EBH

Reputation: 10450

If you want to get the arrary, whithout using a cell-array, use a helper function:

a = '123456abced5421f';
b = @(n) a((n-1)*8+1:(n*8));

Now you can type:

>> b(1)
ans =
    '123456ab'
>> b(2)
ans =
    'ced5421f'

And if you want less or more than 8 elements, just set this as a variable:

m = 16; % or any other integer number
b = @(n) a((n-1)*m+1:(n*m));

The advantage of this method is that it consumes no memory (the helper function is negligible), as you don't create any new variable.


If you want to be able to access several elements in b in one call, than it's better to use a temporary array for that (with row indexing as suggested in @Wolfies answer):

m = 8;
tmp = reshape(a,m,[]).';
b = @(n) tmp(n,:);

Then you can type:

>> b(1:2)
ans =
  2×8 char array
    '123456ab'
    'ced5421f'

Upvotes: 2

Wolfie
Wolfie

Reputation: 30101

You can use reshape to turn your string into a character matrix, i.e. with some number of rows and 8 columns:

a = '123456abced5421f';
b = reshape(a,8,[]).'
>> b = 
     ['123456ab'
      'ced5421f']

Then access each row (8 character string) using standard row indexing

b(1,:) % Row 1, all columns
>> ans = '123456ab'

If you really wanted to just be able to access each row using a single index, you must use cell arrays. To convert b to the desired cell array we can use mat2cell.

c = mat2cell(b, [1 1], 8);

Then indexing is easy

c{1}
>> ans = '123456ab'

All together without defining b, and making it generic:

% number of elements in a must be divisible by 8
c = mat2cell(reshape(a,8,[]).', ones(1, numel(a)/8), 8);

Upvotes: 2

Related Questions