0

Here's my code:

N = 1:999;

for i = N
    if rem(i,3) == 0 || rem(i,5) == 0
        v(i,1) = i
    end      
end

Te problem is that I get an Array with some zeros in, but I just want an an arraywith the values comforming to my conditions.

How can I fix it?

Thank you!

2
  • 1
    I don't understand your question. What is the output you are expecting? Commented Jun 16, 2014 at 18:38
  • N=1:999; then v=(rem(N,3)==0)|(rem(N,5)==0);. Is that what you want? Or are you wanting: v= N( (rem(N,3)==0) | (rem(N,5)==0) ); Commented Jun 16, 2014 at 18:40

2 Answers 2

2

I think the OP is looking for a result like:

v= N( (rem(N,3)==0) | (rem(N,5)==0) );

though without looping... :-)

Sign up to request clarification or add additional context in comments.

6 Comments

In case you're curious, your answer is 72x faster than mine. : )
!! :-). Obviously there might be a reason the OP needs loops, but I love to look for ways to NOT use them. You (@Fletch) are right to leave your loop there in case that is what the OP wants but it is always fun to think of ways to create a solution without loops.
Are you on the Code Review SE site? You should check it out, lots of stuff like this on there.
@Fletch... no, haven't been. Will be now. Thanks! Years ago (many, many years ago) Mathworks had contests (maybe still do) to produce the most efficient/compact code. It was a lot of fun.
@Fletch, on that note, I learned Python years ago by doing the projecteuler.net problems. Lots of fun. (Unfortunately, Project Euler is now offline).
|
0

I'm assuming that you're using a loop for a reason, and am not removing it from my solution. However, loops should be avoided where possible.

If I understand your question, you're trying to store only those values of i which correspond to a true conditional evaluation. You're problem is that you're using i as your index value inside the assignment statement. Use the end index keyword. Like so:

N = 1:999;
v = [];

for i = N
    if rem(i,3) == 0 || rem(i,5) == 0
        v(end+1) = i
    end      
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.