How can I use a variable for formatting?

6 ビュー (過去 30 日間)
Rosario Frontino
Rosario Frontino 2022 年 4 月 14 日
コメント済み: Rosario Frontino 2022 年 4 月 14 日
Hi.
I have this line of code:
address = num2str(str2double(string(dec2bin(find(strcmp(dictionary,content(1:end-1)))))),'%04d');
It works, but I would like that the 4 is taken from a variable.
In particular, my variable is
numBits = ceil(log2(length(phrases)));
Is there a way to do so? Thanks

採用された回答

Les Beckham
Les Beckham 2022 年 4 月 14 日
編集済み: Les Beckham 2022 年 4 月 14 日
You can also use %*d, like this
for k = 1:5
fprintf('%*d\n', k, 2*k); % the first argument (k) is the field width, 2*k is the value to print
end
2 4 6 8 10
Documentation is here
By the way, why are you converting to string and then to double and then back to a string?
  5 件のコメント
Les Beckham
Les Beckham 2022 年 4 月 14 日
編集済み: Les Beckham 2022 年 4 月 14 日
You are welcome. @Star Strider is correct, sprintf is the right way to go.
If an answer in the forum solves your problem, it is considered gracious to accept it. If not please add a comment to request additional clarification. Thanks.
Rosario Frontino
Rosario Frontino 2022 年 4 月 14 日
Yeah it works by using sprintf. Thanks you both

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by