2

Assuming size_of_array < n, to iterate through array elements multiple times, normally I would use something like (in C++):

for (size_t i = 0; i < n; ++i)
{
    elem = arr[ i % size_of_arr ];
} 

If arr = {1, 2, 3};, for elem I would get:

1 2 3 1 2 3 ...

However, in MATLAB / Octave indexes start from 1 and:

for i = 1 : n

  elem = arr( mod( i, length(arr) + 1) );
end

so when n == length(arr) I get an error:

error: arr(0): subscripts must be either integers 1 to (2^31)-1 or logicals

How is this done when indexes start from 1?

4
  • 2
    The idiomatic form for that is mod(i-1,n)+1 (I call it 1-based modulus). So, perhaps elem = arr(mod(i-1, length(arr))+1); works for you (I'm not sure what you are trying to achieve) Commented Sep 5, 2017 at 15:19
  • 2
    never use length, it returns the length of the longest dimension. Instead, use numel (number of elements). Commented Sep 5, 2017 at 15:47
  • error: arr(0): The zero is what Matlab is trying to yell at you about. Commented Sep 5, 2017 at 19:26
  • @LuisMendo Thanks for the helpful comment, it worked perfectly. If you are interested for the use, check : codereview.stackexchange.com/questions/174876/… Commented Sep 5, 2017 at 19:58

1 Answer 1

5

In c++ you would do

arr[ i % size_of_arr]

where the inner index i % size_of_arr is in range [0 size_of_arr-1]

In MATLAB, i is in range [1 size_of_arr], thus just change to

mod( i-1, numel(arr) ) + 1

the first bit (mod( i-1, numel(arr))) makes sure that the index is inside [0 size_of_arr-1], and the you just need to add 1 to that.

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

1 Comment

Thank you! So, what we do is offsetting the index to zero-origin and adjusting the result of modulo operation to start from 1 and on, right?

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.