Filter löschen
Filter löschen

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

13 Ansichten (letzte 30 Tage)
Logan Davis
Logan Davis am 26 Sep. 2016
Kommentiert: Logan Davis am 26 Sep. 2016
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.

Akzeptierte Antwort

James Tursa
James Tursa am 26 Sep. 2016
Bearbeitet: James Tursa am 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,[]);
  1 Kommentar
Logan Davis
Logan Davis am 26 Sep. 2016
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by