Find and convert characters in cell array to numeric values
10 views (last 30 days)
Show older comments
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 Comment
Stephen23
on 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))))
Accepted Answer
Ameer Hamza
on 14 Nov 2020
Edited: Ameer Hamza
on 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 Comments
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!