Question

Is there any way for me to vectorize this?

for i = 1:totSamples
    sec(i,1)    = str2double(data{4}{i,1}(end-1:end));
    min(i,1)    = str2double(data{4}{i,1}(end-4:end-3));
    hour(i,1)   = str2double(data{4}{i,1}(1:end-6));
end

I tried using this solution: https://stackoverflow.com/a/8370368/1583025 but I get this error:

Error using end Incorrect cell or structure reference involving "end". Most likely cause is a reference to multiple elements of a cell or structure followed by >additional subscript or structure references.

Error in file (line 64) sec(:,1) = reshape(sscanf(sprintf('%s#', data{4}{:,1}(end-1:end)), '%g#'), size(data{4}));

Was it helpful?

Solution

I solved the problem using cellfun:

secs = cellfun(@(x) x(end-1:end),data{4}(:),'UniformOutput',false);
mins = cellfun(@(x) x(end-4:end-3),data{4}(:),'UniformOutput',false);
hours = cellfun(@(x) x(1:end-6),data{4}(:),'UniformOutput',false);

sec(:,1)    = reshape(sscanf(sprintf('%s#', secs{:}), '%g#'), size(secs));
min(:,1)    = reshape(sscanf(sprintf('%s#', mins{:}), '%g#'), size(mins));
hour(:,1)   = reshape(sscanf(sprintf('%s#', hours{:}), '%g#'), size(hours));

EDIT:

This is a faster way that I found to do it. The cellfuns were taking too long, so I exploited MATLAB's lazy copying:

time    = reshape(sscanf(sprintf('%s#',data{4}{1:totSamples}),'%d:%d:%d#'), 3,[])';
sec     = time(:,3);
min     = time(:,2);
hour    = time(:,1);

clear time;

OTHER TIPS

Have you thought about datevec? It can actually be done in one line:

I assumed your data and cell structure looks like:

% example data
data{4}{1,1} = '05:20:42'
data{4}{2,1} = '06:22:42'
data{4}{3,1} = '07:24:42'

then just do:

[~,~,~,hour,min,sec] = datevec(data{4},'HH:MM:SS')

returns:

hour =

     5
     6
     7


min =

    20
    22
    24


sec =

    42
    42
    42

Maybe some slightly modifications are necessary, but that's the way. Probably also faster.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top