1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

MATLAB, separate odds and evens from matrix

  1. Jan 29, 2015 #1
    1. The problem statement, all variables and given/known data

    Given variable b that contains a row vector of length 10, assign the contents of the odd indeces in b to variable odd , and assign the contents of the even indeces of b to variable even.

    Examples:

    Input b = [8 -3 0 7 -6 -3 1 8 7 -2]
    Output odd = [8 0 -6 1 7]
    even =[-3 7 -3 8 -2]


    2. Relevant equations


    3. The attempt at a solution

    b is some arbitrary matrix




    O = mod(b,2);
    odd = b(O)


    E = ~mod(b,2);
    even = b(E)

    What's weird is that it works for b(E) but b(O) yields and error: Subscript indices must either be real positive integers or logicals.
     
  2. jcsd
  3. Jan 29, 2015 #2

    RUber

    User Avatar
    Homework Helper

    I am not sure that mod is the best command to use for this purpose. You are just looking to split the matrix into 2 parts based on whether or not the index is odd or ever, right?
    You essentially want something that looks like:
    b = [8 -3 0 7 -6 -3 1 8 7 -2];
    O=[1,3,5,7,9];
    E=[2,4,6,8,10];
    odd = b(O)
    even=b(E)
    The mod function was returning a logical index of whether or not the value was odd or even.
     
  4. Jan 29, 2015 #3
    But it has to be true for any arbitrary matrix of any length of numbers :/.
     
  5. Jan 30, 2015 #4
    You want to generate the sequences 1,3,5,... and 2,4,6,... to use as indices for your matrix. Do you know of any easy way to do that in MATLAB? Hint: The colon operator.
     
  6. Jan 30, 2015 #5

    RUber

    User Avatar
    Homework Helper

    For arbitrary length arrays, you can call length(b) to get your ending value. Or as milesyoung said, it might be more straightforward to use odd = b([1:2:end]) to count by twos using the colon.
     
  7. Jan 30, 2015 #6
    Ah ok, got it. Thanks!
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: MATLAB, separate odds and evens from matrix
  1. Even and odd functions (Replies: 10)

  2. Matlab - Banded Matrix (Replies: 1)

Loading...