1

I have a datetime array with sunrise hour (whole_set_sr), a datetime array with sunset hour (whole_set_ss), and a datetime array with lots with whole calendar data (tm_whole_date). All of them have the same number of elements, so position 1 should be tested against position 1, position 2 should be tested with position 2 and so on..

I am trying to create a binary array with the same number of elements, in which it returns 1 if the element in tm_whole_date is >= the sun rise hour (whole_set_sr) AND <= the sun set hour (whole_set_ss), and 0 if it is out of the these conditions.

I have attempted the following:

    date_list = [];
date_indexes = [];
numel(whole_date)

for i = 1:numel(tm_whole_date)
    if (tm_whole_date(i,1) >= whole_set_sr(i,1)) && tm_whole_date(i,1) <= whole_set_ss(i,1)
            bin_x = 1
    else
        bin_x = 0
    end

    date_list(i) = bin_x
end

It is giving me an array (date_list) full of zeros when there should be values meeting the condition and returning 1.

Also, I need to create a list with the indexes of the positions of 1 values in the whole set of datetime tm_whole_date . (to know based on indexes which elements meet the criteria).

I dont know what it going wrong here and I would appreciate very much some help.

Thanks!

0

1 Answer 1

2

The brilliant thing about MATLAB is you can operate on entire arrays without looping.

after_sunrise = tm_whole_date >= whole_set_sr;
before_sunset = tm_whole_date <= whole_set_ss;
date_list = after_sunrise & before_sunset;

should be all you need to get a logical array (array of true and false / 0 and 1)

Or in one line:

date_list = tm_whole_date >= whole_set_sr  & tm_whole_date <= whole_set_ss;

Make sure that whole_set_sr and whole_set_ss actually contain the entire datetime though, because otherwise the tm_whole_date >= whole_set_sr and tm_whole_date <= whole_set_ss comparisons won't yield what you expect.

The added bonus of this way over looping and appending to an array is that it's much much faster.

Once you've got your logical array, getting the indices that are true is as simple as using find

date_indices = find(date_list);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! It solved my problem in a much easier way.

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.