Search code examples
matlabconsoleprintfnewlineerror-logging

Not getting a new line when using fprintf


I wrote a small function for the pyhtagorean value:

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

It works correctly, but after it returns, the '>>' is on the same line as my output, rather than a fresh line beneath the output. This is only the case for the fprintf. Here:

>> pyth([1 2;3 4],[5 6;7 8])
ans =
    5.0990    6.3246
    7.6158    8.9443
>>
>> pyth([1 2],[1 2;3 4])
Error: Input sizes are not equal>> 

How can I fix this?


Solution

  • fprintf is typically for writing to files (hence the f in the beginning). When writing to (text) files, the way to ensure OS-independent line breaks is to add \r\n (aka CRLF, or [char(10) char(13)]) at the end of your string. It appears that when printing to the console, this is not important (i.e. \n also works in MATLAB running on Linux).

    Several tips:

    • You can use disp or display instead, as they add the newline character for you.
    • If you want to display an error, why not use error?
    • If you use fprintf for printing errors, you might want to start by fprintf(2, ... ) as this will print the text to stderr, making it error-colored (typically red).