Filter löschen
Filter löschen

How can I extract an array of numbers from a text-formatted cell array of strings.

3 Ansichten (letzte 30 Tage)
I have read some data from a spreadsheet. The values are times, but formatted with s, m or h as a suffix to indicate seconds, minutes or hours. see example below,
I'd like to convert all of them to seconds, with NaN for the blank ones.
Is there an elegant way to do this?
Like this:
{'20s' }
{'15m' }
{0×0 char }
{'24s' }
{0×0 char }
{'44s' }
{'3h' }
{'40m' }
{'20s' }
{0×0 char }
{'14s' }

Akzeptierte Antwort

Stephen23
Stephen23 am 26 Apr. 2024
Bearbeitet: Stephen23 am 26 Apr. 2024
C = {'20s';'15m';'';'24s';'';'44s';'3h';'40m';'20s';'';'14s'}
C = 11x1 cell array
{'20s' } {'15m' } {0x0 char} {'24s' } {0x0 char} {'44s' } {'3h' } {'40m' } {'20s' } {0x0 char} {'14s' }
F = @(t)prod(sscanf(t,'%f'));
V = cellfun(F,regexprep(C,{'h$','m$','^$'},{' 3600',' 60','NaN'},'emptymatch'))
V = 11x1
20 900 NaN 24 NaN 44 10800 2400 20 NaN
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Weitere Antworten (2)

Voss
Voss am 26 Apr. 2024
data = {
'20s'
'15m'
''
'24s'
''
'44s'
'3h'
'40m'
'20s'
''
'14s'
};
C = regexp(data,'(\d+)([hms])','tokens','once');
idx = ~cellfun(@isempty,C);
C = vertcat(C{idx});
val = str2double(C(:,1));
[~,unit] = ismember(C(:,2),{'s','m','h'});
result = NaN(size(data));
result(idx) = val.*60.^(unit-1);
disp(result)
20 900 NaN 24 NaN 44 10800 2400 20 NaN 14

dormant
dormant am 14 Mai 2024
Thanks. Both of you helped.

Kategorien

Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange

Produkte


Version

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by