I have a cell array in Matlab:
strings = {'one', 'two', 'three'};
How can I efficiently calculate the length of all three strings? Right now I use a for loop:
lengths = zeros(3,1);
for i = 1:3
lengths(i) = length(strings{i});
end
This is however unusable slow when you have a large amount of strings (I’ve got 480,863 of them). Any suggestions?
You can also use:
It will not be faster, but makes the code clearer.
Regarding the slowness, you should first run the profiler to check where the bottleneck is. Only then should you optimize.
Edit: I just recalled that ‘length’ used to be a built-in function in cellfun in older Matlab versions. So it might actually be faster! Try
Edit(2) : I have to admit that my first answer was a wild guess. Following @Rodin s comment, I decided to check out the speedup.
Here is the code of the benchmark:
First, the code that generates a lot of strings and saves to disk:
Then, the benchmark itself:
And the results are:
Wow!! The ‘length’ syntax is about 30 times faster than a loop! I can only guess why it becomes so fast. Maybe the fact that it recognizes
lengthspecifically. Might be JIT optimization.Edit(3) – I found out the reason for the speedup. It is indeed recognition of
lengthspecifically. Thanks to @reve_etrange for the info.