lnmaurer
lnmaurer

Reputation: 1727

Can you increment a slice in python?

I'm trying out numpy by porting over some code I wrote in matlab/octave. In matlab, I can define the equivalent of a python slice, and then increment it as needed. For example, in my matlab code I have

HXx_range = 1:NHXx;
HXy_range = 1:NHXy;

blah blah blah

Hx(HXx_range, HXy_range) = Da(Hx_media(HXx_range, HXy_range)).*Hx(HXx_range, HXy_range) + Db(Hx_media(HXx_range, HXy_range)).*(Ez(HXx_range,HXy_range) -   Ez(HXx_range,**HXy_range+1**));
Hy(HYx_range, HYy_range) = Da(Hy_media(HYx_range, HYy_range)).*Hy(HYx_range, HYy_range) + Db(Hy_media(HYx_range, HYy_range)).*(Ez(**HYx_range+1**,HYy_range) - Ez(HYx_range,HYy_range));
Ez(EZx_range, EZy_range) = Ca(Ez_media(EZx_range, EZy_range)).*Ez(EZx_range, EZy_range) + Cb(Ez_media(EZx_range, EZy_range)).*(Hy(EZx_range,EZy_range) - Hy(**EZx_range-1**,EZy_range) + Hx(EZx_range,**EZy_range-1**) - Hx(EZx_range,EZy_range));

The terms in '**'s (like 'HXy_range+1') are they key parts; HXy_range+1 is equal to 2:(NHXy+1). In python, I can define a slice in a similar way:

HXx_range = slice(0, NHXx)

However, HXx_range+1 gives me an error. Of course, I can just make a new slice for that, but it's not as clean. Is there a way around this?

Thanks.

Upvotes: 2

Views: 1159

Answers (2)

unutbu
unutbu

Reputation: 879819

If you define your HXy_range as a numpy array, then you can increment it as desired. If and when you wish to use it as a slice, you can form slice(*HXy_range):

In [26]: HXy_range = np.array([1,10])

In [27]: HXy_range+1
Out[27]: array([ 2, 11])

In [28]: slice(*(HXy_range+1))
Out[30]: slice(2, 11, None)

Upvotes: 3

Michael Hoffman
Michael Hoffman

Reputation: 34334

No, Python slice instances are immutable. To use standard slice instances, you must create a new one each time. Unfortunately, you can't subclass slice either.

Upvotes: 1

Related Questions