cell2mat not working when cell array of type char has numbers of different lengths

12 vues (au cours des 30 derniers jours)
Hello - I read in header and data information from files using xlsread. The text fields are returned in single column in a cell array of type char (for example "2014abc1-5ab" or "303abc2-5ab"). I need to separate the first set of digits, and I'd like it to be ultimately in a numeric array.
I current do:
[A, B] = xlsread('data.xls');
C = regexp(B,'\d*','match', 'once');
D = cell2mat(C);
E = str2num(D);
when B = {'2014abc1-5ab'; '2024abc1-5ab'}; The code works as desired. when B = {'2014abc1-5ab'; '303abc1-5ab'}; The code crashes in the cell2mat function. I've traced the problem to the 2014 and 303 being a different number of digits. Ultimately, I'd just like a column of the first numbers in B. B = [2014; 303]. I'm open to any suggestions to make the whole process cleaner.
Thanks!

Réponse acceptée

Andrei Bobrov
Andrei Bobrov le 2 Avr 2014
c = regexp(B,'^\d*','match');
out = str2double([c{:}]');

Plus de réponses (2)

Chandrasekhar
Chandrasekhar le 2 Avr 2014
Modifié(e) : Chandrasekhar le 2 Avr 2014
In the second case the B{1} has 12 characters where as B{2} has only 11 characters . this is making an inconsistent matrix when cell2mat command is used. A matrix with 1st row containing 12 columns and 2nd row containing 11 columns cannot be created.

Dishant Arora
Dishant Arora le 2 Avr 2014
[A, B] = xlsread('data.xls');
C = regexp(B, '\d*', 'match', 'once');
E = cellfun(@str2num, C, 'Un', 1);

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by