Create a variable string array with different number of sig figs based on GUI dropdown

9 ビュー (過去 30 日間)
I have a GUI that has a drop down to change the number of sig figs used in the GUI.
p = 0.105;
n = 25;
%sigFigs = str2double(app.SigFigDropdown.Value);
sigFigs = 3;
if sigFigs == 1
s = sprintf("%.1f (N=%d)", p, n);
elseif sigFigs == 2
s = sprintf("%.2f (N=%d)", p, n);
elseif sigFigs == 3
s = sprintf("%.3f (N=%d)", p, n);
else
s = sprintf("%.2f (N=%d)", p, n);
end
disp(s)
I'd like to simplify the code if possible to make it where the sig figs is a variable in the sprintf call or something similar to that. For example, something like what is below where the x is variable based on the value that is selected in the GUI dropdown but I know that won't actually work where the integer next to the %. is variable as well.
s = sprintf("%.xf (N=%d)",x=sigFigs, p, n);
Unsupported use of the '=' operator. To compare values for equality, use '=='. To pass name-value arguments using the name=value format, provide these arguments after all other inputs.
0.10 (N=25)
disp(s)

採用された回答

Dyuman Joshi
Dyuman Joshi 2023 年 12 月 16 日
Use asterick to provide a value for field width -
p = 0.105;
n = 25;
%sigFigs = str2double(app.SigFigDropdown.Value);
for sigFigs = 1:3;
fprintf('The output for sigFigs = %d', sigFigs)
% v
s = sprintf("%.*f (N=%d)", sigFigs, p, n);
disp(s)
end
The output for sigFigs = 1
0.1 (N=25)
The output for sigFigs = 2
0.10 (N=25)
The output for sigFigs = 3
0.105 (N=25)
  1 件のコメント
Patrick Kelly
Patrick Kelly 2023 年 12 月 19 日
This is great. I never realized it was already implemented in sprintf. Thanks.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by