Reputation: 1260
Simple Matlab code: e.g A(5+(1:3))
-> gives [A(6), A(7), A(8)]
In the above, A
is a vector or a matrix. For instance:
A = [1 2 3 4 5 6 7 8 9 10];
A(5+(1:3))
ans =
6 7 8
Note that MATLAB indexing starts at 1, not 0.
How can i do the same in Python?
Upvotes: 0
Views: 73
Reputation: 117876
You are looking for slicing behavior
A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> A[5:8]
[6, 7, 8]
If A
is some function that you want to call with parameters 6
, 7
, and 8
, you could use a list comprehension.
answers = [A(6+i) for i in range(3)]
Upvotes: 3
Reputation: 3829
You want to do two things.
First, create a range (5 + (1:3))
which could be done in Python like range(number)
.
Second, apply a function to each range index. This could be done with map
or a for
loop.
The for
loop solutions have been addressed, so here's a map
based one:
result = map(A,your_range)
Upvotes: 1
Reputation: 112
in python u can do it easily by A[5:5+3] . u can reference the values 5 and 3 by variables also like b=5 c=3 a[b:b+c]
Upvotes: 0
Reputation: 1828
If you are trying to use subscripts to create an array which is a subset of the whole array: subset_list = A[6:8]
Upvotes: 0
Reputation: 2104
Use a list comprehension:
x = 5
f = 1 # from
t = 3 # till
print [x+i for i in range(f,t+1)]
Upvotes: 0