2

I have the following numeric matrix in MATLAB: A = [3 2 7; 9 1 4; 5 6 8]; I want to sum all elements that are greater than 5 and are also even. I need to do this without using a loop, and store the result in a variable. I am looking for a correct, concise, and efficient one-liner solution that is scalable for larger matrices. The expected output for this problem is 14 (6+8).

My current attempt is: sum(A(A>5)) This code correctly filters for elements greater than 5, but it doesn't consider the "even" condition. The result I get is 34 (7+9+6+8+4), which is incorrect.

3
  • 1
    Do you know the logical AND operator (&)? That is what you need to combine the two conditions. To see if something is even you can test the remainder of the division (rem) by two. Commented Sep 22 at 11:46
  • 1
    Based on your previous (now deleted) question it feels like you're just incrementally asking a set of homework problems, you might find it insightful to read this post before asking more like this. MATLAB has really good documentation, have you tried using the free on-ramp to get started with the basics? Commented Sep 22 at 13:42
  • Thanks for the suggestion, I appreciate it. This isn't for a homework assignment, but a personal project I'm working on. However, your advice to check out the MATLAB documentation and free on-ramp is very helpful, and I will definitely do that. I just wanted to make sure my approach to combining these two conditions was correct. If you have any further guidance, that would be great. Commented Sep 22 at 20:28

1 Answer 1

3

You can include a logical search on the even/odd numbers using mod:

sum(A(A>5 & mod(A,2)==0))
Sign up to request clarification or add additional context in comments.

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.