Reputation: 41
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?
Upvotes: 0
Views: 287
Reputation: 30047
You can just use str2num
:
f = str2num( "[123 456]" )
% f = [123, 456]
Upvotes: 1
Reputation: 41
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.
Upvotes: 2
Reputation: 18177
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
.
Upvotes: 0