how do i write a function that take a vector and only displayes prime elements

I have a homework where i have to write a function that takes in a vector x and outputs a vector p that only has prime elements
This is what i managed to do so far:
tf=isprime([4 3 6 7 1 2 4 6 8 9]) tf = 1×10 logical array
0 1 0 1 0 1 0 0 0 0
Im kinda new to matlab

回答 (2 件)

Rik
Rik 2018 年 5 月 10 日
You are very close. The only thing you need to do is use the logical vector to keep only prime elements. BTW, are you sure you are allowed to use the isprime function for your homework assignment?
x=[4 3 6 7 1 2 4 6 8 9];
tf=isprime(x);
x_output=x(tf);
A helpful resource to learn using Matlab is available here.

5 件のコメント

Ahmad al-falahi
Ahmad al-falahi 2018 年 5 月 10 日
yeah thanks i did this x=[91 39 87 51 89 37 65 29 41 43 97]
t=isprime(x)
p=t.*x
but its not a program, i think i will use your ways and see what happens XD
Ahmad al-falahi
Ahmad al-falahi 2018 年 5 月 10 日
yeah this is better, now the zeroes are gone, thanks
Ahmad al-falahi
Ahmad al-falahi 2018 年 5 月 10 日
Oh no, sorry they want us to Use the "if, if-elseif, for and while commands
Rik
Rik 2018 年 5 月 10 日
Well, then it's time to read the documentation for the while function, if and elseif. Just type
doc while
in your command window to open the documentation viewer.
Use a for or a while loop to loop through all elements of the input vector (hint: start from the back of your vector). Then use conditional statements to remove elements that are not prime.
I don't know a way to give you better hints without making your homework for you.
Ahmad al-falahi
Ahmad al-falahi 2018 年 5 月 10 日
thanks for the help man.

サインインしてコメントする。

KSSV
KSSV 2018 年 5 月 10 日
A = [4 3 6 7 1 2 4 6 8 9] ;
idx=isprime(A)
iwant = A(idx)
Read about MATLAB logical indexing.

2 件のコメント

Ahmad al-falahi
Ahmad al-falahi 2018 年 5 月 10 日
thanks
Ahmad al-falahi
Ahmad al-falahi 2018 年 5 月 10 日
Oh no, sorry they want us to Use the "if, if-elseif, for and while commands. do you know how to do that ?

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

製品

タグ

質問済み:

2018 年 5 月 10 日

コメント済み:

2018 年 5 月 10 日

Community Treasure Hunt

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

Start Hunting!

Translated by