1

In matlab one can do

for i = 2:10
 array(i) = array(i-1) + value
end 

How can I replicate this in python?

4
  • I'm not very good at matlab, what is value here? Is it the old value of array(i)? Commented Dec 31, 2021 at 12:08
  • That's just a random value that we want to add to the array in each cycle.! I also don't understand this quite well. I was sent a Matlab script with this on it. Furthermore, I am trying to decipher it and implement it in python. I believe that this is similar to the array += value where you have something like k=k+1 Commented Dec 31, 2021 at 12:40
  • MATLAB can grow a matrix by simply assigning new indices. With numpy you need to initial the array to fill size first. But we need more context to come up with a good numpy or python solution. For example np.cumsum([value1,value2, value3...]). Commented Dec 31, 2021 at 17:51
  • Check out Manlais answer, stackoverflow.com/a/70560707/7031021 Commented Jan 3, 2022 at 1:06

2 Answers 2

4

In python it will be:

for i in range(1,10):
   array[i] = array[i-1] + value

Keep in mind that in python, indexing starts from 0.

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

2 Comments

Why 9? If I understand correctly, matlab's 10 is inclusive, but range isn't, so you need 10 here to stop after index 9 (the 10th 0-indexed element)
@Expurple, You're right! Thank You for spotting it. Already fixed.
0

You can do something like this in python:

But you should also pay attention to one point: That the number of indexes in Python starts from zero while in MATLAB from one

for i in range(2,10):
    array[i] = array[i-1] + value

have a good time!

Comments

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.