0

I'm trying to convert an input string "[f1 f2]", where both f1 and f2 are integers, to an array of two integers [f1 f2]. How can I do this?

3 Answers 3

2

I have found a way by using sscanf:

f = sscanf(s, "[%d %d]", [1 2]);

where s is the array-like string and f the new array of integers.

Sign up to request clarification or add additional context in comments.

Comments

1

You can just use str2num:

f = str2num( "[123 456]" )
% f = [123, 456]

Comments

0

You can use indexing together with strsplit()

my_str = "[32 523]";
split_str = strsplit(my_str, ' ');  % split on the whitespace
% The first cell contains "[32" the second "523]"
my_array = [str2num(split_str{1}(2:end)) str2num(split_str{1}(1:end-1))]
my_array = 
           32  523

When you have more numbers in your string array, you can lift out the first and last elements of split_str out separately (because of the square brackets) and loop/cellfun() over the other entries with str2num.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.