interpolate_string

版本 1.0.1 (1.8 KB) 作者: Cris Luengo
Applies string interpolation (also known as variable expansion or variable substitution) in a string.
19.0 次下载
更新时间 2022/3/26

查看许可证

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.

引用格式

Cris Luengo (2024). interpolate_string (https://www.mathworks.com/matlabcentral/fileexchange/108829-interpolate_string), MATLAB Central File Exchange. 检索来源 .

MATLAB 版本兼容性
创建方式 R2021b
兼容任何版本
平台兼容性
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
版本 已发布 发行说明
1.0.1

Fixed minor typos in help text, improved description, no changes to code.

1.0.0