Repeated printing of output when the code is run. How to change to print it only once?

61 views (last 30 days)
Output is printing twice in both command window as well as inside the plot. It is the same for fprintf and sprintf.
Example :
a=mean(x);
fprintf('Mean=%f',a);
OUTPUT :
Mean=value
Mean=value
How to solve this?

Accepted Answer

Cedric
Cedric on 31 Aug 2015
Edited: Cedric on 1 Sep 2015
This is because MEAN works along a dimension (the 1st by default) and not over the full array. See below:
>> A = rand(3, 4)
A =
0.8147 0.9134 0.2785 0.9649
0.9058 0.6324 0.5469 0.1576
0.1270 0.0975 0.9575 0.9706
>> m1 = mean(A) % Implicitly along dim 1.
m1 =
0.6158 0.5478 0.5943 0.6977
>> m1 = mean(A, 1) % Explicitly along dim 1.
m1 =
0.6158 0.5478 0.5943 0.6977
>> m2 = mean(A, 2) % Explicitly along dim 2.
m2 =
0.7429
0.5607
0.5382
So what you are passing to S/F-PRINTF is a vector and not a scalar, and S/F-PRINTF repeats the format for all elements of the vector. If you want a to be the mean of all elements of x, use for example
a = mean( x(:) ) ;
Now a is a scalar. If you really need a mean per column (along dim 1) and to print it, update your formatSpec in the call to S/F-PRINTF, e.g.
a = mean( x ) ; % With x a two columns array.
fprintf( 'Mean per column = [%f, %f]', a ) ;
or
fprintf( 'Mean per column =\n' ) ;
disp( a ) ;

More Answers (0)

Categories

Find more on Numeric Types in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!