Prime number sum from cell array
古いコメントを表示
I'm currently trying to write a function that will input a cell array and will take an input such as getPrimeSum({1, 3, 7, 7, 'a'}) and return the sum of the prime numbers while ignoring characters and ignoring duplicates. The desired answer for that input example would be 10.
I'm relatively new to matlab and hung up on how to handle my input being inside the curly brackets because much of the code I am trying to use will not accept my input in that form. The second hangup is I'm not sure how to convert it since cell2mat() returns an error due to the character that is in the input. I thought I found a way around it with my first line which made the code usable, but my current code is returning 0 and I'm not sure why. Any advice is appreciated. My current progress is below.
function res = getPrimeSum(cArr);
cArr(cellfun(@ischar,cArr)) = {nan};
myArr = cell2mat(cArr);
filter1 = unique(myArr);
filter2 = isstrprop(myArr, 'digit');
onlyNumbers = myArr(filter2);
primeSum = sum(isprime(onlyNumbers));
res = primeSum;
end
採用された回答
その他の回答 (1 件)
The variable myArr is a double array. Then isstrprop(myArr, 'digit') is FALSE for all elements, because onbly CHARs can be digits. Simply omit this test:
function X = getPrimeSum(C)
C(cellfun(@ischar, C)) = {nan}; % Better: C(cellfun(@ischar, C)) = []
X = unique(cell2mat(C));
S = sum(isprime(X));
end
Use the debugger to examine such problems: Set a breakpoint in the first line of the code and step through your function line by line.
カテゴリ
ヘルプ センター および File Exchange で Cell Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!