interpolate_string
Version 1.0.1 (1.76 KB) by
Cris Luengo
Applies string interpolation (also known as variable expansion or variable substitution) in a string.
String interpolation (see https://en.wikipedia.org/wiki/String_interpolation) is a much more convenient way to include data in strings than what fprintf provides, or than concatenating bits of string:
- fprintf puts the stuff being replaced into the string far away from where it will be replaced, making the resuling code hard to read.
- Concatenating strings has become a bit easier since the string type was introduced, but still requires a lot of quotes.
String interpolation exists in many languages, but not in MATLAB. Hopefully some day MATLAB will have an interpolated string type. Until then, you can choose to use this function.
If you want, you can rename the function to have a shorter name, so it's easier to use. For example, you could call it f, to match Python's syntax for interpolated strings:
>> f = @interpolate_string;
For example:
>> disp("cos(4) = " + cos(4) + ", didn't you know?")
cos(4) = -0.65364, didn't you know?
>> fprintf("cos(4) = %f, didn't you know?\n", cos(4))
cos(4) = -0.653644, didn't you know?
>> disp(f("cos(4) = {cos(4)}, didn't you know?"))
cos(4) = -0.6536, didn't you know?
Some more examples:
>> f = @interpolate_string;
>> s = 3.4; p = 'foo'
>> f("The value of s is {s}, and that of p is {p}!")
ans =
"The value of s is 3.4000, and that of p is foo!"
>> f("The value of s is {s}, \{this is not replaced}.")
ans =
"The value of s is 3.4000, {this is not replaced}."
Note! This function is not fast. Use it for convenient syntax, but don't expect a performance similar to fprintf.
Cite As
Cris Luengo (2024). interpolate_string (https://www.mathworks.com/matlabcentral/fileexchange/108829-interpolate_string), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Created with
R2021b
Compatible with any release
Platform Compatibility
Windows macOS LinuxTags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!Discover Live Editor
Create scripts with code, output, and formatted text in a single executable document.