uout = 'centimeters';
case 'miles'
fun = @(mi)mi .* 1.6093;
uout = 'kilometers';
case 'pounds'
fun = @(lb)lb .* 0.4536;
uout = 'kilograms';
case 'pints'
fun = @(pt)pt .* 0.4731;
uout = 'litres';
case 'ounces'
fun = @(oz)oz .* 28.35;
uout = 'grams';
end
val = fun(str2num(valin));
valout = [num2str(val) ' ' uout];
end
At the command line, call the convertMe function from regexprep, passing in values for
the quantity to be converted and name of the imperial unit:
regexprep('This highway is 125 miles long', ...
'(\d+\.?\d*)\W(\w+)', '${convertMe($1,$2)}')
ans =
'This highway is 201.1625 kilometers long'
regexprep('This pitcher holds 2.5 pints of water', ...
'(\d+\.?\d*)\W(\w+)', '${convertMe($1,$2)}')
ans =
'This pitcher holds 1.1828 litres of water'
regexprep('This stone weighs about 10 pounds', ...
'(\d+\.?\d*)\W(\w+)', '${convertMe($1,$2)}')
ans =
'This stone weighs about 4.536 kilograms'
As with the (??@ ) operator discussed in an earlier section, the ${ } operator has
access to variables in the currently active workspace. The following regexprep
command uses the array A defined in the base workspace:
2 Program Components