No BSD License  

Highlights from
repfloat

image thumbnail
from repfloat by Michael Robbins
Replaces a number in a string, while preserving the string length.

repfloat.m
% RepFloat
% REPLACE FLOAT, PRESERVE STRLEN

clear all;
L = 5000
for i=0:5:L-1
   st{i+1} = '\@Sens. Deflection: V 128.2021 nm/V';
   st{i+2} = '\Spring constant: 0.124';
   st{i+3} = '\@Sens. TUNA Current: V 10.00000 pA/V';
   st{i+4} = '\@Sens. Fast Scan setpoint: V 1.000000 V/V';
   st{i+5} = '\@Sens. Friction: V 1.000000';
end;
newval = repmat([0.666 155.1 0.05 1.02 0.8955],1,L./5);
ss=st';
nv=newval;

for speed_loop=1:2
    clear str fmt vallen str_final;
    tic;
    switch speed_loop
    case 1
        str = strrep(strrep(st,'%','%%%%'),'\','\\\\');
        fmt = regexprep(str,'(:*)(\d+\.\d*|\.\d+)(.*)','$1%%%ds$3','tokenize');
        vallen = cellfun('length',str(:))-cellfun('length',fmt(:))+5;
        for i=1:length(newval)
            str_final{i} =sprintf(sprintf(fmt{i},vallen(i)),sprintf('%g',newval(i)));
        end
    case 2
        str = strrep(strrep(st,'%','%%%%'),'\','\\\\');
        fmt = regexprep(str,'([\D\.]*)(\d+\.\d*)(.*)','$1%%%ds$3','tokenize');
        vallen = cellfun('length',str(:))-cellfun('length',fmt(:))+5;
        for i=1:length(newval)
            str_final{i} =sprintf(sprintf(fmt{i},vallen(i)),sprintf('%g',newval(i)));
        end
    end;
    results(speed_loop).time=toc;
    results(speed_loop).in=st';
    results(speed_loop).out=str_final';
end;
fprintf('My 6 liner''s speed = %6.3fs\n',results(1).time);
fprintf('My quicker''s speed = %6.3fs\n',results(2).time);

Contact us