Search code examples
matlabmat-file

How to get numeric value(Decimals) from a string name


I currently have a list of mat files labeled from P0.01.mat- P10.mat and would like to get numeric value of the selected .mat file. what i have currently gives me just from P1.mat to P10.mat. When i run this for a string of P0.01.mat its returns the number 1.

    Files=dir(fullfile(datapath,'*.mat'));
    numfiles=length(Files);
    results=cell(numfiles,1);
    for k = 1:numfiles
    results{k}=Files(k).name; % lists all the names available
    end
    Ace=[results];
    A=Ace(1);  %selects the string 

     B = regexp(A,'\d*','Match');  %gets the numerals in the string 
     for ii= 1:length(B)
         if ~isempty(B{ii})
         Num(ii,1)=str2double(B{ii}(end));
         else
         Num(ii,1)=NaN;
         end
   end
   Num    

Solution

  • To match a number with an optional decimal point in it, use the regex string [0-9]*\.?[0-9]+.

    B = regexp(A,'[0-9]*\.?[0-9]+','Match');  %gets the numerals in the string
    

    Reference: A: Parsing scientific notation sensibly? (which contains regexp for a more complex floating-point value representation).