Issues converting a Cell to a numerical array

Hi, I am trying to get the sum of all the prime unique nummbers in cell. I am having trouble converting the cell to a numerical array so that I can use the sum and prime functions on my inputs. The inputs are normally formated as ({1, 3, 7, 7, 'a'}) and matlab ether does not recognize these values as nummbers or can not convert a cell that has both nummbers and letters into a numerical array. TO be specific I am looking for a way to remove the letter from the cell and covert the rest of the cell to an array that I can use mathmatical operations on.

답변 (1개)

the cyclist
the cyclist 2021년 2월 25일
편집: the cyclist 2021년 2월 25일
Here is one way that may work for you:
C = {1, 3, 7, 7, 'a'};
N = cell2mat(C(cellfun(@isnumeric,C)))
N = 1×4
1 3 7 7

댓글 수: 4

This seems to covert the cell into a 3x1 matrix but when I try to use primes on the new matrix N I get an error saying N must be a scalar. Do you know how to fix this?
The documentation for primes indicates that it expects a scalar (not vector) input, and then reports all primes up to and including it.
isprime(N)
will tell you whether each element is prime.
Sorry to keep bothering you but the end product of the function is the sum of all the prime numbers in the cell. I was thinking there would be two ways to do this one was just to use primes(N) to get just the prime numbers and then sum that but that is where the error ocurs telling me that N has to be a scalar. The other is to use an if isprime statment inside a while loop to check if each number is prime and then add the number to a varible if it is prime and keep doing that till the program has read each nummber. I am pretty new to matlab so the seocnd options is dificult for me. Thats why I was hoping to just use primes(N) instead. If you have any adive on eather option I would really apreciate it.
C = {1, 3, 7, 7, 'a'};
N = cell2mat(C(cellfun(@isnumeric,C)));
primeN = N(isprime(N))
primeN = 1×3
3 7 7
lists only the prime numbers from C. You mentioned needing unique values somehow, so you might also need the unique function.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2021년 2월 25일

댓글:

2021년 2월 25일

Community Treasure Hunt

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

Start Hunting!

Translated by