How to assign boundary condition

Suppose I have a vector like the following:
I=[8, 5, 12, 7, 9]
suppose also that for the purpose of some program I need to use the quantity
I(i)
where i is an integer, but not necessarily 0<i<6. I need a function (or a method, possibly a smart one) such that:
I(6)
returns 8 (=I(1))
I(0)
returns 9 (=I(5))
and so on: I(-1) returns I(4), I(-2) returns I(3), ... I(-5) returns I(5)... I(7) returns I(2), ... I(11) returns I(1)...
More exactly: I need periodic condition for the vector I (imagine that I(i) describes some physical quantity of a crystal primitive cell, that's require periodicity).
Note that the function
mod(i,5)
does not the correct job for i<1. How can I "fix" it for this range of i (i<1)?
Sorry for my bad english, and thank you for your help!

 Accepted Answer

The mod function is exactly what you need. But since matlab use 1-based indexing, you need to shift your indices by 1 before and after modding:
boundedindex = mod(index-1, numel(I)) + 1

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!