Effacer les filtres
Effacer les filtres

Find and convert characters in cell array to numeric values

10 vues (au cours des 30 derniers jours)
That Guy
That Guy le 14 Nov 2020
Commenté : Stephen23 le 14 Nov 2020
Im struggling with a portion of a hw problem. Ive been tasked with summing the unique prime numbers in a given cell array. My code works fine except if an element of an array that is a number is entered as a character ie {1, '3', 7, '7', 'a'}, when i run the code with {1, 3, 7, 7, 'a'} it gives me the correct answer.
here is my code so far:
cArr = {1, '3', 7, '7', 'a'};
numind = cellfun(@isnumeric, cArr);
cArr(~numind) = {0};
newarray = cell2mat(cArr);
logicalarray = isprime(newarray);
primeonly = logicalarray.*newarray;
c = unique(primeonly);
ans = sum(c);
is there a way to find characters like '3' and '7' and convert them to doubles so the rest of my code can work properly?
  1 commentaire
Stephen23
Stephen23 le 14 Nov 2020
Simpler:
C = {1, '3', 7, '7', 'a'};
V = str2double(C);
X = cellfun(@isnumeric,C);
V(X) = [C{X}];
V = V(isfinite(V));
S = sum(unique(V(isprime(V))))
S = 10

Connectez-vous pour commenter.

Réponse acceptée

Ameer Hamza
Ameer Hamza le 14 Nov 2020
Modifié(e) : Ameer Hamza le 14 Nov 2020
Try this
cArr = {'b', 7, 13, 21};
char_ind = cellfun(@ischar, cArr);
cArr(char_ind) = cellfun(@str2double, cArr(char_ind), 'uni', 0);
finite_ind = cellfun(@isfinite, cArr);
finites = [cArr{finite_ind}];
logicalarray = isprime(finites);
primeonly = finites(logicalarray);
c = unique(primeonly);
sum(c)
  4 commentaires
That Guy
That Guy le 14 Nov 2020
thanks!
Ameer Hamza
Ameer Hamza le 14 Nov 2020
I am glad to be of help!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by