Home > Software engineering >  String to array in MATLAB
String to array in MATLAB

Time:07-14

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?

CodePudding user response:

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.

CodePudding user response:

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.

  • Related