interpolate_string

버전 1.0.1 (1.76 KB) 작성자: Cris Luengo
Applies string interpolation (also known as variable expansion or variable substitution) in a string.
다운로드 수: 21
업데이트 날짜: 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