How to convert 'comma' to 'dot'?
조회 수: 21 (최근 30일)
이전 댓글 표시
채택된 답변
Thorsten
2016년 6월 16일
편집: Thorsten
2016년 6월 16일
You can use my function fstrrep to replace each . with a , and then use dlmread to read the data:
fstrrep('test22.txt', ',', '.')
data = dlmread('test22.txt')
The m-file:
function fstrrep(filename, oldsubstr, newsubstr, newfilename)
%FSTRREP Replace string in file.
%
%FSTRREP(FILENAME, OLDSUBSTR, NEWSUBSTR, [NEWFILENAME])read each line in
%FILENAME and replaces the string OLDSUBSTR with NEWSUBSTR and writes the
%new line to NEWFILENAME. If the optional argument NEWFILENAME is not
%given, the contents of the original file is changed.
%
%Example: In file 'test.txt', replace each ',' with a '.'
% fstrrep('test.txt', ',' '.')
%
%Thorsten.Hansen@psychol.uni-giessen.de
%%open file to read from and new file to write to
fid1 = fopen(filename, 'r');
if fid1 == -1
error(['Cannot open file ' filename ' for reading.']);
end
if nargin < 4
newfilename = '_temp.txt';
end
fid2 = fopen(newfilename, 'w');
if fid2 == -1
error(['Cannot open file ' newfilename ' for writing.']);
end
%%read line and write changed line to new file
line = fgets(fid1);
while line ~= -1
newline = strrep(line, oldsubstr, newsubstr);
fprintf(fid2, '%s', newline);
line = fgets(fid1);
end
%%close both files
st = fclose(fid1);
if st == -1
error(['Cannot close ' filename '.'])
end
st = fclose(fid2);
if st == -1
error(['Cannot close ' tempfilename '.'])
end
%%replace old file with new file
if nargin < 4
movefile(newfilename, filename)
end
추가 답변 (1개)
Azzi Abdelmalek
2016년 6월 10일
편집: Azzi Abdelmalek
2016년 6월 10일
a=importdata('test2.txt')
b=strrep(a,',','.')
c=cell2mat(cellfun(@str2num,b,'un',0))
댓글 수: 2
Mohamed Asaad
2022년 2월 7일
Hi! This works for me. However when i use files including negative value or Nan, it does not work. I get error message " Conversion to double from struct is not possible."
DGM
2022년 2월 7일
편집: DGM
2022년 2월 7일
The output type of importdata() varies depending on how it manages to split the text based on the specified delimiters. There are probably other ways to do this, but consider this. I've simply renamed the extensions so that they can be uploaded and run here.
A = importdata('Au_1_E_chem_experiment_SPR_angle_offset_after_PEG.txt',' ');
A = strrep(A,',','.'); % convert commas to dots
A = regexp(A,'([^\t]*)','tokens'); % split each line into its elements
B = cellfun(@str2double,vertcat(A{:})); % convert to numeric
B(1:10,:) % show a sample
Similarly for the other file
A = importdata('Au_1_E_chem_experiment_TIR_angle.txt',' ');
A = strrep(A,',','.'); % convert commas to dots
A = regexp(A,'([^\t]*)','tokens'); % split each line into its elements
B = cellfun(@str2double,vertcat(A{:})); % convert to numeric
B = B(2:end,:); % strip off the header
B(55:64,:) % show a sample
참고 항목
카테고리
Help Center 및 File Exchange에서 Convert Image Type에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!