If I have this right, you're only working with PCNN_Y where its value is 1. Then you skip over the first sp instances where it's 1. Then you want to stop after iv_max occourances past sp.
Below is a way to rewrite your loop.
- Find all cases where PCNN_Y_r is 1 (_r is the reshaped vector of the matrix PCNN_Y)
- Skip over the first sp instances of the value 1 (start)
- End after sp+iv_max-1 instances of the value 1 (finish)
This way you don't need to end the parfor loop early. You know the exact start and end of the loop.
Below is an example. I've put dummy values for position, iv, and iv_max -- adjust accordingly.
In this case, we'll assign PCCN_S where position is [3 4 5], but nothing after.