How can I improve speed of strcat in a for loop?
30 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
James Tursa
on 26 Sep 2016
Edited: James Tursa
on 26 Sep 2016
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,[]);
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!