Matlab 使用fprintf时未获得新行
我为pyhtagorean值编写了一个小函数:Matlab 使用fprintf时未获得新行,matlab,console,printf,newline,error-logging,Matlab,Console,Printf,Newline,Error Logging,我为pyhtagorean值编写了一个小函数: function c = pyth(a,b) % Takes two inputs of same size and returns the pythagorean of the 2 inputs if size(a) == size(b) % checks for same size c = sqrt(a.*a + b.*b); % calculates the pythagorean value else fprintf('E
function c = pyth(a,b)
% Takes two inputs of same size and returns the pythagorean of the 2 inputs
if size(a) == size(b) % checks for same size
c = sqrt(a.*a + b.*b); % calculates the pythagorean value
else
fprintf('Error: Input sizes are not equal'); % returns if sizes are not the same
end
它工作正常,但返回后,“>>”与我的输出在同一行,而不是在输出下面的新行。这仅适用于fprintf
。在这里:
>> pyth([1 2;3 4],[5 6;7 8])
ans =
5.0990 6.3246
7.6158 8.9443
>>
如何修复此问题?将\n用于换行符:
fprintf('Error: Input sizes are not equal\n');
fprintf
通常用于写入文件(因此开头的f
)。写入(文本)文件时,确保操作系统独立的换行符的方法是在字符串末尾添加\r\n
(也称为CRLF或[char(10)char(13)]
)。当打印到控制台时,这似乎并不重要(即\n
在Linux上运行的MATLAB中也可以工作)
以下几点提示:
- 当他们为您添加换行符时,您可以使用或
- 如果要显示错误,为什么不使用
- 如果使用
打印错误,您可能需要从fprintf
开始,因为这会将文本打印到stderr,使其显示错误颜色(通常为红色)fprintf(2,…)
fprintf('Error: Input sizes are not equal\n');