How do I remove trailing zeros after rounding a matrix while retaining current rows/columns format?

25 views (last 30 days)
I am trying to display a matrix that with numbers all rounded off to 1 decimal point. Currently when I round, there is a 0 that remains in the hundreths place of each number. I'd like to remove this last zero so that all my numbers only display out to the tenths place.
I have tried using the fprintf function as well as the sprintf function but I always lose the rows/column format of my matrix. Is there a way to round and then shorten an entire matrix of numbers so that there aren't any trailing zeros?
matrix = [1.34, 3.45, 2.34; 0.54, 21.34, 0.34; 11.81, 9.94, 10.02]; %3x3 matrix of data
round_matrix = round(matrix, 1); %3x3 matrix of data rounded to 1 decimal place
%My attempts thus far at removing the trailing zeros
disp_matrix = sprintf('%.1f', rounded_matrix); %This resulted in a string of all of my numbers mashed together
disp_matrix = fprintf('%.1f\n',round(Table_outnumeric)); %This resulted in all of my numbers being converted into a single column

Accepted Answer

Matt J
Matt J on 7 Feb 2018
Edited: Matt J on 7 Feb 2018
How about as follows,
>> disp_matrix = num2str(round_matrix, '%.1f '); disp(disp_matrix)
1.0 0.8
0.5 0.1
To be clear, though, if you want to a matrix displayed to 1 decimal place, you have no choice but to convert it to string/char type. You cannot force MATLAB to display actual numeric matrix objects to arbitrary customized precision. However, see FORMAT for the display options that you do have.

More Answers (1)

Matt J
Matt J on 7 Feb 2018
disp_matrix = sprintf('%.1f ', round_matrix)
  1 Comment
Leslie Franczek
Leslie Franczek on 7 Feb 2018
This answer results in a single row of numbers:
>> matrix = rand(2,2)
matrix =
0.9572 0.8003
0.4854 0.1419
>> round_matrix = round(matrix,1)
1.0000 0.8000
0.5000 0.1000
>> disp_matrix = sprintf('%.1f ', round_matrix)
disp_matrix =
'1.0 0.5 0.8 0.1 '
I ultimately want to retain my 2x2 matrix of the rounded numbers like this:
>> round_matrix = [1.0, 0.8; 0.5, 0.1]
1.0 0.8
0.5 0.1

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!