Find and convert characters in cell array to numeric values

10 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2020-11-14
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

请先登录,再进行评论。

采纳的回答

Ameer Hamza
Ameer Hamza 2020-11-14
编辑:Ameer Hamza 2020-11-14
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 个评论

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by