emil
emil

Reputation: 105

Matlab character to string convertion problem. What function to use?

x = 1234     56789     7654

x(1) is 1, x(2) is 2 and so on... there are 5 spaces in between.. size(x) = 1 23 One row with 23 columns I've tried using num2str, strcat but I cannot club the numbers. y = num2str(x), y = strcat(x)

I want it to be.. x(1) = 1234, x(2) = 56789, x(3) = 7654

What function should I use to accomplish the above?

Upvotes: 4

Views: 1694

Answers (5)

Jurnell
Jurnell

Reputation: 66

The following creates a cell array of strings then follows it up with an application of sscanf.

b = regexp(x,'\d+','match');
y = cellfun(@(a) (sscanf(a,'%d')),b); 

Upvotes: 0

John
John

Reputation: 5913

Just to add another answer to the mix...

y = textscan(x, '%d     %d     %d')

Upvotes: 0

b3.
b3.

Reputation: 7175

STR2NUM works well for this task:

>> x = '1234     56789     7654';
>> x = str2num(x)'

x =

        1234
       56789
        7654

Upvotes: 0

nimrodm
nimrodm

Reputation: 23839

Simple solution is to use sscanf:

x =' 1234     56789     7654'

sscanf(x, '%d')

ans =

    1234
   56789
    7654

Upvotes: 4

carlosdc
carlosdc

Reputation: 12152

There are several ways of performing what you want. One of them is strtok.

x = '1234     56789     7654';
[fst rest] = strtok(x,' ');

Upvotes: 2

Related Questions