フィルターのクリア

Variable precision point for fprintf command set by user input

5 ビュー (過去 30 日間)
Nathan
Nathan 2024 年 2 月 2 日
コメント済み: Walter Roberson 2024 年 2 月 2 日
I am trying to create a variable precision point through an user input to control how many decimal places are shown when displaying the results from the elements of a matrix.
This code is what I current have but would like to make the precision (currently at 10) adjustable:
when I try to replace the .10 with * and set a variable it messes up my code:
I am new to Matlab and would appreciate any help on this so I can input a values to dispaly results to any decimal place value.

回答 (2 件)

Voss
Voss 2024 年 2 月 2 日
編集済み: Voss 2024 年 2 月 2 日
Here's what the documentation for fprintf has to say about this:
"When you specify * as the field precision operator, the other input arguments must provide both a precision and a value to be printed. Precisions and values can be pairs of arguments, or pairs within a numeric array."
So the precisions and values must be in pairs. Example:
M = [1 2 3 4; 5 6 7 8];
precision = 10;
[nrows,ncols] = size(M);
args = zeros(1,2*ncols); % row vector of precision/value pairs
args(1:2:end) = precision; % 1st, 3rd, 5th, etc., elements are the precisions
for ii = 1:nrows
args(2:2:end) = M(ii,:); % 2nd, 4th, 6th, etc., elements are the values from M
fprintf(" %10.*f",args)
fprintf("\n")
end
1.0000000000 2.0000000000 3.0000000000 4.0000000000
5.0000000000 6.0000000000 7.0000000000 8.0000000000
  2 件のコメント
Nathan
Nathan 2024 年 2 月 2 日
Thank you, that works perfectly
Voss
Voss 2024 年 2 月 2 日
You're welcome!

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


Walter Roberson
Walter Roberson 2024 年 2 月 2 日
fprintf( fprintf(' %%10.%df'), precision), Ab(i,:))
  4 件のコメント
Nathan
Nathan 2024 年 2 月 2 日
that worked perfectly as well. Thank you. I'll have to look into the code you created to understand the nesting and fprint/sprint command.
Walter Roberson
Walter Roberson 2024 年 2 月 2 日
It is equivalent to
Format = sprintf(' %%10.%df', precision);
fprintf(Format, Ab(i,:));
The sprintf() computes the format to be used by the fprintf()

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by