フィルターのクリア

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 Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by