You are now following this question
- You will see updates in your followed content feed.
- You may receive emails, depending on your communication preferences.
Add zero decimal digits in order to have all the elements of a matrix with same number of decimal digits
20 views (last 30 days)
Show older comments
How can I add zero decimal digits to a number in order to have the same number of decimal digits in the numbers of a matrix? For instance, if I have only a "27" how can I change it to a "27.000"? I have already tried the function
compose("%.3f",A)
in order to have the same decimal formt of all the elements of matrix A, but it does not work.
Accepted Answer
Walter Roberson
on 4 Dec 2021
Edited: Walter Roberson
on 5 Dec 2021
I already showed you how to use compose with a format to get a fixed number of digits.
14 Comments
Emilio Pulli
on 4 Dec 2021
It does not work, the txt file is not well aligned…numbers have 3 decimal digits but they are not well displaced in the txt file. Look at the txt file that I attached in previous answers
Walter Roberson
on 5 Dec 2021
format long g
A = rand()
A =
0.885883063562536
B = [0 1 15 99 143 987 1024].' + A
B = 7×1
1.0e+00 *
0.885883063562536
1.88588306356254
15.8858830635625
99.8858830635625
143.885883063563
987.885883063563
1024.88588306356
compose("%8.3f", B)
ans = 7×1 string array
" 0.886"
" 1.886"
" 15.886"
" 99.886"
" 143.886"
" 987.886"
"1024.886"
Looks aligned to me ?
Walter Roberson
on 5 Dec 2021
r = rand();
A = [0 1 15 99 143 nan 987 1024 nan nan].' + r;
fmt = "%8.3f"; %important that it is string not character vector
S = standardizeMissing(compose(fmt, A), " NaN")
S = 10×1 string array
" 0.729"
" 1.729"
" 15.729"
" 99.729"
" 143.729"
<missing>
" 987.729"
"1024.729"
<missing>
<missing>
writematrix(S, 'dataset_red2.txt', 'delimiter', 'tab')
!cat 'dataset_red2.txt'
0.729
1.729
15.729
99.729
143.729
987.729
1024.729
Note that here the text NaN in the standardizeMissing call must have the same width as the fixed format -- so in this case where a format width of 8 is forced, there needs to be five spaces before the 'NaN'
Emilio Pulli
on 6 Dec 2021
How can I insert a header in a txt file without deleting the contents and the format of the txt file? I would like simply to insert a header on top of all the columns of data to specify the type of variable on top of ech column
Walter Roberson
on 6 Dec 2021
You cannot. The underlying technology of how text is stored does not permit inserting text without deleting the contents of the file and rewriting the file.
Emilio Pulli
on 6 Dec 2021
How can I sort out the problem? I needs to insert the names of variables per each column....
Walter Roberson
on 6 Dec 2021
Write the header in before the text. Or accept that the technology would require rewriting to end of file.
Emilio Pulli
on 6 Dec 2021
In your opinion, rewriting the file, considering that I need all the afore mentioned constraints on format, blank spaces etc, would create problems?
Walter Roberson
on 6 Dec 2021
Rewriting text files is a bit of a nuisance to do robustly. I would really recommend that you insert the header first.
For example you can use writetable(). Or you can write text to the file and then writematrix with the option to append.
Emilio Pulli
on 6 Dec 2021
Ok thank you Walter! I think that I will simply inser the header after having created the txt file, the effort is the same and in this way I will not add useless lines to my code
Walter Roberson
on 6 Dec 2021
take the result of the standardizeMissing and array2table() with 'VariableNames' set to the header for the column. writetable() the results.
Walter Roberson
on 6 Dec 2021
https://www.mathworks.com/matlabcentral/answers/1601825-how-to-use-ismember-to-check-if-an-inputted-number-exists-in-a-matrix#comment_1868585 has more background about text files.
More Answers (2)
Rik
on 4 Dec 2021
There is a distinction between the way data is stored and how it is displayed.
You can change the data type (double, single, cell, char, etc) to change the underlying data.
You can use functions like fprintf and sprintf to display your data a certain way.
12 Comments
Emilio Pulli
on 4 Dec 2021
I need that a txt file (that I create with the function writematrix) displays data in a certain way. At the moment I am using:
writematrix(string(C), 'dataset_red_lin.txt', 'delimiter', 'tab');
where C is my input cell matrix. But the txt file is not well tabulated because there are some numbers with different number of decimal digits, I want that txt file has well defined columns...
Rik
on 4 Dec 2021
In that case I would suggest switching to fprintf (see the instructions in the documentation). That way you have complete control over the format.
Emilio Pulli
on 4 Dec 2021
Unfortunately I cannot switch to fprintf. This is my code:
v_cutin=2.5;
v_cutout=15;
v_rated=5.5;
v=linspace(v_cutin,v_cutout,15);
omega_rpm=linspace(1,600,200);
dataset_lin=importdata('dataset_lin.mat');
dataset_red_lin=NaN*ones(((length(omega_rpm)/10)+1)*length(v)+length(v)-1,6);
x=1;
row=0;
y=1;
stop=0;
for i=1:length(dataset_lin)
if isnan(dataset_lin(i,1))==0
row=row+1;
stop=0;
elseif isnan(dataset_lin(i,1))==1 && stop<1
step=floor(row/10);
check=mod(row,10);
if check==0
dataset_red_lin(y:1:y+9,:)=compose("%.3f",dataset_lin(x:step:(i-1),:));
dataset_red_lin(y+10,:)=NaN*ones(1,6);
x=i+1;
row=0;
y=y+11;
elseif check>0
dataset_red_lin(y:1:y+10,:)=compose("%.3f",dataset_lin(x:step:(i-check),:));
dataset_red_lin(y+11,:)=NaN*ones(1,6);
x=i+1;
row=0;
y=y+12;
end
stop=stop+1;
elseif stop==1
i=length(dataset_lin);
end
end
A = dataset_red_lin;
C = num2cell(A);
idx = isnan(A);
C(idx) = {''};
writematrix(string(C), 'dataset_red_lin.txt', 'Delimiter', 'tab');
I need the conversion to cell in order to replace the NaN values with blank spaces. However, the resultant txt file is not well tabulated because there are some numbers which has no decimal digits. How do I can figure out the problem?
Rik
on 4 Dec 2021
I don't see why you can't switch. The only thing is that you want to print something blank if there is a NaN. There is no reason why fprintf could not work. It would only replace the last line of your code.
Emilio Pulli
on 4 Dec 2021
Can you please write me the exact piece of code that I have to insert? Because, at the moment, I am not able to figure it out….
Rik
on 5 Dec 2021
The easiest way is to loop through the rows and then the columns.
for row=1:size(A,1)
for col=1:size(A,2)
if col==size(A,2), delim='\n';else delim='\t';end
if isnan(A(row,col))
%what exactly do you want to print here?
else
fprintf(fid,[FormatSpec delim],A(row,col));
end
end
end
Emilio Pulli
on 5 Dec 2021
The problem is that I have to work with cell array C and not the number array A because this latter contains the NaN rows
Emilio Pulli
on 5 Dec 2021
Maybe I can use your loop and then I can turn the A into the cell array C and use the function writematrix to produce the txt file…
Rik
on 5 Dec 2021
If you need to use the C array, you only need to change the indexing and change isnan to isempty. I don't know why you're insisting on writematrix.
Emilio Pulli
on 5 Dec 2021
Edited: Emilio Pulli
on 5 Dec 2021
If I do not convert A into the C cell array, I cannot replace the NaN rows with the blank spaces. And writematrix is the only function that writes a txt file with an input cell array. While fprintf does not work with cell array. Is or clear? Do you want a detailled explanation of the code that I attached?
Rik
on 5 Dec 2021
Did you not see the if statement? The loop I showed will write only 1 value at a time, so you have full control over the format.
But the solution Walter showed you will also work.
Emilio Pulli
on 6 Dec 2021
Thank you man! I use the Walter answer because was faster, but also your advices helped me understanding better the problem! Thank you again for the patience!
G A
on 4 Dec 2021
A = magic(3)
A = 3×3
8 1 6
3 5 7
4 9 2
B = num2str(A,'%.3f\t')
B = 3×17 char array
'8.000→1.000→6.000'
'3.000→5.000→7.000'
'4.000→9.000→2.000'
See Also
Categories
Find more on Text Data Preparation 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!An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom(English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)