How do I make the same output using the fprintf() command instead of disp()?

1 回表示 (過去 30 日間)
Adam Hernandez
Adam Hernandez 2018 年 11 月 14 日
コメント済み: Adam 2018 年 11 月 14 日
Hello, this is my first question on here and I notice Answerers are sometimes frustrated by questions, so I hope this question does not anger anyone. I am trying to use fprintf() instead of the disp() and have the exact same output. Here's the editor window and output:
editor:
A = [1 2 3;4 5 6;7 8 9];
[m,n] = size(A);
for i = 1:m
for j = 1:n
disp(['A(',num2str(i),',',num2str(j),') = ',num2str(A(i,j))])
end
end
output:
>> Practice9
A(1,1) = 1
A(1,2) = 2
A(1,3) = 3
A(2,1) = 4
A(2,2) = 5
A(2,3) = 6
A(3,1) = 7
A(3,2) = 8
A(3,3) = 9
>>
%Also, this is what I attempted to do, but got a 'horzcat' error
%what is that???
A = [1 2 3;4 5 6;7 8 9];
[m,n] = size(A);
for i = 1:m
for j = 1:n
fprintf(['A(','(%s,','%s) = ','%f',i,j,A])
%% disp(['A(',num2str(i),',',num2str(j),') = ',num2str(A(i,j))])
end
end
  6 件のコメント
Adam Hernandez
Adam Hernandez 2018 年 11 月 14 日
Thank you! Very well explained!
Adam Hernandez
Adam Hernandez 2018 年 11 月 14 日
Thank you to everyone for the input!!! It is very much appreciated, especially at this hour.

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

採用された回答

madhan ravi
madhan ravi 2018 年 11 月 14 日
編集済み: madhan ravi 2018 年 11 月 14 日
Replace disp with:
fprintf('A(%d,%d)=%d\n',i,j,A(i,j))
  5 件のコメント
madhan ravi
madhan ravi 2018 年 11 月 14 日
編集済み: madhan ravi 2018 年 11 月 14 日
Adam
Adam 2018 年 11 月 14 日
Well, where you use them you are also encompassing the arguments that are to be inserted in place of the placeholder %d formatting specifiers. These need to be distinct arguments to fprintf, they are not part of the string first argument. Other than that, as madhan ravi says, they are mostly just superfluous if you are putting them only around the initial string part of the argument.
disp is different because you have to put together the combination of bits of the string and numeric components which have to be converted to string yourself, thus you concatenate all these components.
fprintf does that for you via those %d format specifiers so that you can just give a single formatting string, then supply the arguments that will be inserted in-place of those format specifiers. fprintf will handle converting them to the type you request (e.g. %i converts to an integer, %f to float, %s inserts as a string, etc).

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by