Home > Software engineering >  How do I expand a range of numbers in MATLAB
How do I expand a range of numbers in MATLAB

Time:11-03

Lets say I have this range of numbers, I want to expand these intervals. What is going wrong with my code here? The answer I am getting isn't correct :(

intervals are only represented with - each 'thing' is separated by ;

I would like the output to be: -6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 20

range_expansion('-6;-3--1;3-5;7-11;14;15;17-20 ')

function L=range_expansion(S)
% Range expansion
if nargin < 1; 
    S='[]';
end

if all(isnumeric(S) | (S=='-')  | (S==',') | isspace(S))
    error 'invalid input';
end
ixr = find(isnumeric(S(1:end-1)) & S(2:end) == '-') 1;
S(ixr)=':';
S=['[',S,']'];
L=eval(S) ;

end


ans =

    -6    -2    -2    -4    14    15    -3

CodePudding user response:

You can use regexprep to replace ;by , and the - that define ranges by :. Those - are identified by them being preceded by a digit. The result is a string that can be transformed into the desired output using str2num. However, since this function evaluates the string, for safety it is first checked that the string only contains the allowed characters:

in = '-6;-3--1;3-5;7-11;14;15;17-20 '; % example
assert(all(ismember(in, '0123456789 ,;-')), 'Characters not allowed') % safety check
out = str2num(regexprep(in, {'(?<=\d)-' ';'}, {':' ','})); % replace and evaluate
  • Related