MATLAB: Delete every second element in array

delete second elementsine

Hello everyone,
for my research project I'm trying to let a robot move a sine curve (only in a z axis up and down). The problem is, that if two points are very close to each other (i.e. 0.2mm) the robot gets really slow, stays still for like half a second and then moves on, so the total time isn't the same. Now in my code I'm trying to delete every second point (and then double the time in between these points in RoboDK), but I can't figure out how to do this in an if loop. Like really important is, that the extreme values must be kept, so the robot can move to the endpositions and I'll get a sine curve.
Here's my code so far:
clear;
A = 50;
t = 0.05;
x = 0:0.05:10*pi;
y = -A*sin(x) + 389.387; %389.387 is the start position of the robot, he only moves in z-axis
T = (1:length(x))*t;
figure(1)
plot(T,y,'.')
xlabel('time')
ylabel('distance')
hold on
%%
newpoints = zeros(1,(length(y)));
newpoints(1,1) = y(1,1);
for i = 3:length(y)
if (y(i) - y(i-1)) < 0.2 %Check, if distance under 0.2mm
if (sign(y(i)-y(i-1))) ~= (sign((y(i-1)-y(i-2)))) %Check if it's an extreme value, because of sign change
newpoints(i-1) = y(i-1);
elseif i == 1:2:length(y) %This is where the trouble begins, I dont't know how to tell Matlab to delete every second point
newpoints(i-1) = [];
end
end
end
figure(1)
plot(T,newpoints,'r.')
xlabel('time')
ylabel('distance')
I'm using Matlab R2020 for academic use. I'd be really glad if you guys could help me out!

Best Answer

To delete every second element in an array starting with element #2,
x(2:2:end) = [];
or starting with element #1,
x(1:2:end) = [];
But to ensure you never delete the endpoints,
x(2:2:end-1) = [];
To preserve indexing, you can insert NaN values instead of removing elements,
x(2:2:end) = nan;
x(1:2:end) = nan;
x(2:2:end-1) = nan;