Shury
Shury

Reputation: 578

Replace numbers on even positions in sorted array

I have an array sorted in ascended order. I want to replace the biggest m numbers found even positions in the array with 0.

My algorithm that I thought looks like this:

k=1;
for j=n:1  %%starting from last position to first
    if(rem(j,2)==0 && (k<=m))  %%checking if the position is even & not getting over m numbers
        B(j) = 0;
        k = k + 1;
    end
end

Can anyone point out why it is not working? Thank you!

Upvotes: 1

Views: 86

Answers (2)

Stewie Griffin
Stewie Griffin

Reputation: 14939

I believe this should do the trick. This works for vectors with both odd and even number of elements.

n = numel(B);
B((n-mod(n,2)):-2:(n-mod(n,2)-2*M)) = 0

or

n = mod(numel(B),2);
B((end-n:-2:end-n-2*M)) = 0

I prefer Shai's solution, but if your vector is huge, and M is relatively small, I would go with this approach, as it avoids creating a vector of length numel(B)/2

Upvotes: 1

Shai
Shai

Reputation: 114856

A bit more complex

even = (n-rem(n,2)) : -2 : 1; % even indices in descending order
B( even(1:m) ) = 0; % set to zero

Note how n-rem(n,2) ensures that we start from the last even index into B.

PS,
It is best not to use j as a variable name in Matlab.

Upvotes: 1

Related Questions