Azzera filtri
Azzera filtri

Find and convert characters in cell array to numeric values

10 visualizzazioni (ultimi 30 giorni)
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 Commento
Stephen23
Stephen23 il 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

Accedi per commentare.

Risposta accettata

Ameer Hamza
Ameer Hamza il 14 Nov 2020
Modificato: Ameer Hamza il 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 Commenti

Accedi per commentare.

Più risposte (0)

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by