Explain this line of code (Index)

Hi, can someone explain to me what these line of code mean?
L = 2400
i = ceil(L*rand(1))
x = periodic_index(i, L, 1);
I understand what the code in the first two lines mean. My main concern is with the code in the last line.
Thanks in advance.

1 Comment

periodic_index is a user defined function i guess

Sign in to comment.

 Accepted Answer

The second line does not always give 1. It gives a number between 1 and 2400 rounded up to the next higher integer. Look:
L = 2400 ;
i = ceil(L*rand(1))
i = 1778
The code
x = periodic_index(i, L, 1);
basically picks out a value from column 2400 (which is L in the second index position) from a row randomly chosen from the range 1-2400 (which is i).
The code is poorly written for many reason:
  1. No comments
  2. Using i (the imaginary variable as a variable name)
  3. No check that L does not exceed the number of rows in periodic_index
  4. L and x are non-descriptive variable names (What the heck does L stand for?)
Be careful if you're taking programming advice from that person. Try this instead:

2 Comments

Thanks a lot for the answer! Really appreciate the comments for the code.
OK, please click "Accept this answer" for the one, best answer. Thanks in advance. 🙂

Sign in to comment.

More Answers (1)

KSSV
KSSV on 18 Feb 2022
Edited: KSSV on 18 Feb 2022
L = 2400 ; % a number
i = ceil(L*rand(1)) % ceil(rand(1)) always gives 1
x = periodic_index(i, L, 1); % From periodic_index array extract 2400x2400x1 element if it is array

2 Comments

I thought rand(1) gives a random value from 0 to 1. So why does the second line always give 1?
Yes rand/ rand(1) will give you a random number lying betweem (0,1), as the function ceil is used, result will be 1. You can check it by yourself.
for i = 1:100
ceil(rand)
end
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1
ans = 1

Sign in to comment.

Products

Release

R2021b

Community Treasure Hunt

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

Start Hunting!