Clear Filters
Clear Filters

MATLABにもPy​thonのforma​t関数に似たものはあ​りますか?

10 views (last 30 days)
Kohei Yoshino
Kohei Yoshino on 3 Apr 2024
Edited: Kenjiro Sugimoto on 4 Apr 2024
【やりたいこと】
MATLABでcsvファイルを読み込む際、'A_gait.csv', 'B_gait.csv', 'C_gait.csv', ...のように似たようなファイル名で管理しているため、A、B、Cのところだけを変更して簡単に処理できるようにしたいと思っています。以前Pythonを使用していたときは、format関数があったため、以下のように処理することができました。
name = {'A', 'B', 'C'};
data = readmatrix('A_gait.csv'); % この形式ではなく、
data = readmatrix('{}_gait.csv'.format(name));% このような形式で表したい
% Pythonのformat関数一例
a = 123
b = 'abc'
print('{} and {}'.format(a, b))
%ans = 123 and abc
MATLABでも文字列を処理する際に似たような関数があればその使い方含めて教えてくださると幸いです。

Accepted Answer

Kenjiro Sugimoto
Kenjiro Sugimoto on 3 Apr 2024
Edited: Kenjiro Sugimoto on 4 Apr 2024
sprintf() はいかがでしょうか(Pythonの format() というよりはC言語の printf()/sprintf() に近いものですが)。文字列の中に数字等を埋め込めこんだ結果を返します。第1引数が書式を表す文字列で、第2引数以降が挿入したい値です。書式文字列中に整数用のプレースホルダ「%d」や文字列用のプレースホルダー「%s」を仕込んでおくと、そこに数値や文字列を入れてくれます。必要に応じて桁数指定などもできます。詳しくは参考リンクをご覧ください。
name = "A";
sprintf("%s_gait.csv", name)
ans = "A_gait.csv"
a = 123;
b = "abc";
sprintf("%d and %s", a, b)
ans = "123 and abc"
  1 Comment
Kohei Yoshino
Kohei Yoshino on 3 Apr 2024
ありがとうございます。思い通りの処理ができました。

Sign in to comment.

More Answers (0)

Tags

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!