在Matlab中,在我看来disp
和fprintf
命令都非常相似,因为它们都显示以显示您告诉它的内容。这两个命令有什么区别?
答案 0 :(得分:1)
对于disp
,它显示变量的值。
例如
>> a = 1; disp(a)
1
另一个例子。
>> disp('example')
example
请注意,'example'
可以看作是变量
参考:https://www.mathworks.com/help/matlab/ref/disp.html
对于fprintf
,如果您要谈论在屏幕上显示,则格式为
fprintf(formatSpec,A1,...,An)格式化数据并将结果显示在 屏幕。
与disp
的区别在于,除非您指定格式字符串,否则它不会显示变量的值
例如,如果您倾向于显示变量的值,则会出现错误
>> a = 1; fprintf(a)
Error using fprintf
No format string.
您需要指定格式字符串。例如,格式字符串为'The value of a is %d\n'
a = 1; fprintf('The value of a is %d\n',a)
The value of a is 1
如果您正在谈论将数据写入文本文件,则格式为
fprintf(fileID,formatSpec,A1,...,An)将formatSpec应用于所有 以列顺序排列数组A1,... An的元素,并将数据写入到 文本文件。 fprintf使用在调用中指定的编码方案 打开。
例如
fileID = fopen('exp.txt','w');
fprintf(fileID,'The number is %d\n',1);
fclose(fileID);
使用type
命令查看文件的内容。
>> type exp.txt
The number is 1
fprintf
还可以返回fprintf写入的字节数。 Refer to this answer