Find and convert characters in cell array to numeric values
12 ビュー (過去 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
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))))
採用された回答
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 Center および File Exchange で Logical についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!