EkEhsaas
EkEhsaas

Reputation: 93

Converting cell array of strings with number arrays to matrices

I have cell array which has strings with different length:

rr ={'1 2 5';
     '5 6 1';
     '12 56 2';
     '12 1';
     '343 2 -5 1 5';
     '1  5  3  2 0'}

I want to make different matrices of numbers and not string based on the strings length:

a1 = [1 2 5; 5 6 1; 12 56 2]
a2 = [12 1]
a3 = [343 2 -5 1 5; 1  5  3  2 0]

I have a large set and my actual data will have many matrices like a1,a2,a3.

Upvotes: 1

Views: 87

Answers (1)

Robert Seifert
Robert Seifert

Reputation: 25232

Here is one way:

rr ={'1 2 5';
     '5 6 1';
     '12 56 2';
     '12 1';
     '343 2 -5 1 5';
     '1  5  3  2 0'}

%// convert 
x = cellfun(@(x) sscanf(x,'%f'), rr,'uni',0)
%// count
n = cellfun(@numel,x)
%// distribute
s = accumarray(n,1:numel(n),[],@(ii) {x(ii)} )
%// remove empty elements
s = s(~cellfun('isempty',s)) 
%// assign
m = cellfun(@(y) [y{:}].' ,s, 'uni',0)

%// last step I'd try to avoid
[a,b,c] = m{:};

a =

    12     1


b =

    12    56     2
     5     6     1
     1     2     5


c =

     1     5     3     2     0
   343     2    -5     1     5

I'd recommend you to avoid the last step and keep working the cell array m, as you don't know in advance how many a1,a2 ... and so on you need. Structs are also a good option.

Upvotes: 2

Related Questions