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

29 次查看(过去 30 天)
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 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by