필터 지우기
필터 지우기

How can I improve speed of strcat in a for loop?

조회 수: 13 (최근 30일)
Logan Davis
Logan Davis 2016년 9월 26일
댓글: Logan Davis 2016년 9월 26일
I am new to MATLAB and am trying to turn the constitution into binary.
When I run the code below, It takes around a minute to run. Having tested it with the strcat part commented out the code runs fairly fast so I believe the concatenation part of the code is the slower part.
I attempted to pre-allocate an array of chars that is 7 times the length of the constitution file in order to increase the speed of the for loop but this didn't work and produced incorrect results. Below is the code I attempted to use:
file = fopen('constitution.txt');
constitution = fscanf(file,'%c');
Asc = cell(1,length(constitution));
code = char(zeros(1,length(constitution)*7)); %attempt at speeding up was unsuccesful and slowed down code/produced incorrect results
%code = ''; Original code, produced correct results but was very slow.
for i = 1:length(constitution)
Asc{i} = dec2bin(constitution(i),7);
code = strcat(code,Asc{i});
end
fclose(file);
My question I guess then is how can I correctly allocate the string in order to not have the variable 'code' be resized each iteration and hopefully speed up the code in the process.

채택된 답변

James Tursa
James Tursa 2016년 9월 26일
편집: James Tursa 2016년 9월 26일
Do you need "code" inside the loop for some reason? If not, why not construct it once outside the loop? E.g., something like this
Asc = cell(1,length(constitution));
for i = 1:length(constitution)
Asc{i} = dec2bin(constitution(i),7);
end
code = strcat(Asc{:}); % concatenate everything at once
Or maybe this is all you need to do?
code = reshape(dec2bin(constitution,7)',1,[]);
  댓글 수: 1
Logan Davis
Logan Davis 2016년 9월 26일
Wow, Thank you so much that worked very wonderfully and for some reason I didn't even think of that. Thanks for the quick reply and I hope you have a great day.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by