replace comma with dot in large array

조회 수: 55 (최근 30일)
JB
JB 2017년 8월 18일
댓글: Image Analyst 2017년 8월 18일
Please help, I'm new to matlab coding. I have a array like this
data={'250,1000' '-6,52796' '322,683' '1,50367'
'250,0500' '-6,54959' '322,695' '1,50379'
'250,0000' '-6,63267' '322,711' '1,50395'}
except that it is very large (4500 lines). I want to replace all the commas with dots and convert to a data matrix. So far I have this:
data = strrep(data, ',', '.');%replace ´,´ with ´.´
data=cellfun(@str2num,data);
which can do the trick but it is very slow. Any suggestions to speed up the process?

채택된 답변

Guillaume
Guillaume 2017년 8월 18일
Well, the slow bit is probably your cellfun(@str2num). Replacing that by:
data = str2double(data);
would probably be faster. The strrep step is already as fast as it can be in matlab.
If you want faster, you need to modify your import process but if I recall correctly matlab is not very good as coping with ',' decimal separator.
  댓글 수: 1
JB
JB 2017년 8월 18일
the code: dataS1 = str2double(strrep(dataS1, ',', '.'));
did the job in 0.21 sec. Thanks a lot. My old code was 3.6 sec...

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2017년 8월 18일
4500 is not very big. I ran this code
% Create sample data
n = 4500
data = cell(1, n);
for k = 1 : n
data{k} = '123,456';
end
% Now do the replacement.
tic;
data = strrep(data, ',', '.'); % Replace ´,´ with ´.´
toc;
% celldisp(data);
fprintf('Done!\n');
and got this:
Elapsed time is 0.002293 seconds.
Two milliseconds seems fast to me. Exactly how fast do you need it?
  댓글 수: 2
JB
JB 2017년 8월 18일
편집: JB 2017년 8월 18일
Hi Image analyst. It sure is faster than my code, but it does not convert to a data matrix. I might have made a mistake...
Image Analyst
Image Analyst 2017년 8월 18일
"data matrix" is so ambiguous that we don't know what it is. ANY kind of matrix in MATLAB could be considered a data matrix, from a character matrix to a cell array to a table to a regular double matrix. Your "data" is a cell array and so is, in fact, already a data matrix. If you want a vector of doubles, you can do
d = str2double(data);
as Guillaume first showed. Did you ever figure out why yours took so long while my running of your code took only 2 ms?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by