Azzera filtri
Azzera filtri

how can I change a sequence so that the values of the sequence are zero if the the result division by 2 is not an integer in MATLAB?

3 visualizzazioni (ultimi 30 giorni)
for example if x=[0 1 2 3 4]
I want to generate seqeunce
y= [0 0 2 0 4]

Risposta accettata

Fangjun Jiang
Fangjun Jiang il 30 Giu 2023
x=[0 1 2 3 4];
y=x;
index=mod(x,2)~=0;
y(index)=0
y = 1×5
0 0 2 0 4

Più risposte (1)

John D'Errico
John D'Errico il 30 Giu 2023
Learn to use MATLAB. As a good start, that means you need to do the Onramp tutorial.
And since this is very likely homework, or part of a homework assignment, I won't do it for you.
But how would you do this in MATLAB?
Break a problem that is too big for you to handle into smaller problems. First, how can you know if the elements of a vector are divisible, by say 5?
x = 0:10;
What does this tell you?
mod(x,5) == 0
ans = 1×11 logical array
1 0 0 0 0 1 0 0 0 0 1
What do the elements that are 1 tell you? How about the zeros?
Now, suppose you just divided x by 5?
x/5
ans = 1×11
0 0.2000 0.4000 0.6000 0.8000 1.0000 1.2000 1.4000 1.6000 1.8000 2.0000
Finally, what would you get, IF you multiplied those two results, term by term? Can you do that last step? Don't forget to use parens.
And, of course, change the problem, since I was dividing by 5, not 2.
  3 Commenti
mohamed imrayed
mohamed imrayed il 30 Giu 2023
x = 0:10;
x.*(mod(x,2)==0)
ans = 1×11
0 0 2 0 4 0 6 0 8 0 10
You're right its much more simple when you break it down, thanks alot!
John D'Errico
John D'Errico il 30 Giu 2023
EXCELLENT. The trick on all these things is to split them up. See if you can get close to your goal. Then take the result you have, and look to see if there is a way to get the rest of the way there.

Accedi per commentare.

Categorie

Scopri di più su Testing Frameworks in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by