mat
mat

Reputation: 2617

MATLAB converting efficiently a matrix into a formated cell string

I want to convert very large matrixes into formated cells string. I've created the following code, however it is very slow and I would like to improve it as much as possible.

tic
r = rand(1000,1000);
p = rand(1000,1000);

a = cellstr(num2str(r(:),'%+.2f'));
a = strrep(a,'+',' ');
a = strrep(a,'0.','.');
a = strcat(a(:),{'  '});
idx_05 = find(p<.05);
idx_01 = find(p<.01);
a(idx_05) = strrep(a(idx_05),'  ','* ');
a(idx_01) = strrep(a(idx_01),'* ','**');
a = reshape(a,size(r));
toc

Elapsed time is 9.968568 seconds.

Upvotes: 1

Views: 34

Answers (1)

Matt
Matt

Reputation: 13953

Since the problem seems to be located in the strcat-command, we can find an alternative to achieve the same result. The strrep-command seems to execute quite fast, so let's use it once more.

Put some extra characters in your format-string used by num2str. After replace them with the spaces. This way we don't need strcat.

a = cellstr(num2str(r(:),'%+.2fAA'));
a = strrep(a,'AA','  ');

Here are my timings:
mean of 10 measurements per method (i5, 2.5GHz)

11.41s  ->  OP's code
 5.07s  ->  proposed solution

This equals an improvement of approximately 44.4%.

Upvotes: 1

Related Questions