이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
Add zero decimal digits in order to have all the elements of a matrix with same number of decimal digits
조회 수: 13 (최근 30일)
이전 댓글 표시
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.
채택된 답변
Walter Roberson
2021년 12월 4일
편집: Walter Roberson
2021년 12월 5일
I already showed you how to use compose with a format to get a fixed number of digits.
댓글 수: 14
Emilio Pulli
2021년 12월 4일
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
2021년 12월 5일
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
2021년 12월 5일
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
2021년 12월 6일
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
2021년 12월 6일
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
2021년 12월 6일
How can I sort out the problem? I needs to insert the names of variables per each column....
Walter Roberson
2021년 12월 6일
Write the header in before the text. Or accept that the technology would require rewriting to end of file.
Emilio Pulli
2021년 12월 6일
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
2021년 12월 6일
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
2021년 12월 6일
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
2021년 12월 6일
take the result of the standardizeMissing and array2table() with 'VariableNames' set to the header for the column. writetable() the results.
Walter Roberson
2021년 12월 6일
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.
추가 답변 (2개)
Rik
2021년 12월 4일
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
Emilio Pulli
2021년 12월 4일
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
2021년 12월 4일
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
2021년 12월 4일
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
2021년 12월 4일
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
2021년 12월 4일
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
2021년 12월 5일
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
2021년 12월 5일
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
2021년 12월 5일
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
2021년 12월 5일
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
2021년 12월 5일
편집: Emilio Pulli
2021년 12월 5일
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
2021년 12월 5일
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
2021년 12월 6일
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
2021년 12월 4일
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'
참고 항목
카테고리
Help Center 및 File Exchange에서 Text Data Preparation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- 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)
아시아 태평양
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)