0

I have a code like the following:

def infball_proj(mu, beta):
    newmu = np.zeros(mu.shape)
    if len(mu.shape) == 2:
        for i in range(mu.shape[0]):
            for j in range(mu.shape[1]):
                if np.abs(mu[i,j]) > beta:
                    newmu[i,j] = np.sign(mu[i,j]) * beta
                else:
                    newmu[i,j] = mu[i,j]
        return newmu
    elif len(mu.shape) == 1:
        for i in range(mu.shape[0]):
            if np.abs(mu[i]) > beta:
                newmu[i] = np.sign(mu[i]) * beta
            else:
                newmu[i] = mu[i]
        return newmu

Is there a smarter way to do this so I don't have to write the 2 different cases? It would be nice if I could have a version that scales to an arbitrary dimension (i.e. numbers of axes).

2 Answers 2

1

Something like this should do the job:

newmu = np.where(np.abs(mu) > beta, np.sign(mu) * beta, mu)

Or, if I get the logic right,

newmu = np.minimum(np.abs(mu), beta) * np.sign(mu)
Sign up to request clarification or add additional context in comments.

1 Comment

Some commentary on your answer would help with clarity. Please translate why. Also, you should elaborate on what "get the logic right" means as a difference from the related above.
1
mu[np.abs(mu)>beta] = np.sign(mu[np.abs(mu)>beta]) * beta

np.abs(mu)>beta will create a boolean array which can then be used for boolean indexing.

The LHS mu[np.abs(mu)>beta] will return a view of the elements being selected by the boolean indexing and can be assigned to the value your want, that is, the RHS.

REMEMBER: Try to avoid for-loop of NumPy array as it is very inefficient.

4 Comments

Some commentary on your answer would help with clarity
@EricHodonsky Does it really help if I add “Something like this should the job” in my answer? I doubt.
Unfortunately flip doesn't get you very far in the internet community. You have a nice score at time of this comment of 1,339. That means you've been here for a while, you've helped others, and been helped. When prompted for clarity, it is in the answer, not that you have answered at all. Please describe WHY you have written the code this way, and HOW it answers their question. Remember, SO Q&A isn't just for the OP and whom ever is selected as the correct answer. Now to answer your flip, in triage I am only presented with one answer, I don't see them all.
@EricHodonsky You are correct int his. I agree. More clarification has been given

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.