Lorz.Astro
Lorz.Astro

Reputation: 23

Separate string and perform math operations in Matlab

Hello I have the following problem:

I have the string num1 = '02 12 28.27'

I would like to perform operations with the numbers separately but first I need to separate the numbers, for example:

num_1 = 02

num_2 = 12

num_3 = 28.27

I was trying the following:

c = textscan(num1,'%f %f %f', 'Delimiter', ' ')

num1 = c{1}

num2 = c{2} 

num3 = c{3} 

I just got an empty vector.

Thanks in advance for your help!

Upvotes: 1

Views: 49

Answers (2)

Suever
Suever

Reputation: 65430

You will want to use str2double to convert the string. Then you don't have to mess around with textscan and you will have more consistent behavior if your input string isn't in quite the format you expected. If a particular value is non-numeric or non-parseable, a NaN will be returned.

values = str2double(num1);

If you really want the result in a cell array (as you have shown), you can do that conversion with num2cell.

cells = num2cell(values);

And if you really need them in separate variables, you can use deal to do that assignment for you.

[num1, num2, num3] = deal(cells{:});

While you can do that, I would highly recommend keeping them in a more manageable data structure like a cell array or numeric array than as separate variables in your workspace.

Upvotes: 0

rayryeng
rayryeng

Reputation: 104504

Suever's answer is good, but if you actually want to get your code going, don't put any spaces in the format string. You've already specified that you're expecting spaces in between each number with the 'Delimiter' flag so there's no need to insert an additional space in between the expected numbers to be read.

Therefore, just do this:

num = '02 12 28.27';
c = textscan(num,'%f%f%f', 'Delimiter', ' ');  %// Change
num1 = c{1};    
num2 = c{2};    
num3 = c{3}; 

We thus get:

>> num1

num1 =

     2

>> num2

num2 =

    12

>> num3

num3 =

   28.2700

Upvotes: 1

Related Questions