Alemex
Alemex

Reputation: 145

is a way to quickly convert long cell character data to number matrix?

Below is the sample code that describe my issue.

ff= [{'1 2 3 4 5'};{'2 2 3 4 2'};{'3 2 3 4 3'};{'4 2 3 4 4'}];
YY=[];
for i=1:length(ff)
    xx=str2num(ff{i,1});
    YY=[YY;xx];
end

similar to the sample code my real length of ff length is very large and it is taking longer to finish the conversion. is there a way to make it faster?

Upvotes: 0

Views: 55

Answers (1)

Suever
Suever

Reputation: 65460

Your solution is going to be particularly slow since you keep expanding the size of YY every time through the for loop.

To optimize this, you could first convert your cell array of strings into one long string using strjoin. Then you can apply str2num to this entire string at once and reshape the result.

YY = reshape(str2num(strjoin(ff)), [], numel(ff)).'

%   1   2   3   4   5
%   2   2   3   4   2
%   3   2   3   4   3
%   4   2   3   4   4

If your version of MATLAB doesn't have strjoin, you can always replace it with sprintf

YY = reshape(str2num(sprintf('%s ', ff{:})), [], numel(ff)).';

Another option would be to convert each entry of the cell array to numbers using cellfun and num2str and then concatenate the result along the first dimension.

values = cellfun(@num2str, ff, 'UniformOutput', false);
YY = cat(1, values{:});

The first option is about twice as fast since you call num2str only once and the memory needed to store the temporary string created by strjoin is going to be less than the space required to store the same data as a numeric datatype (double).

Upvotes: 2

Related Questions