I am wanting to delete these entries of vector x when x = 0. How do I do this. Matlab gives me an error right now saying index cannot exceed 38 but I don't know what's wrong.

1 view (last 30 days)
clear all
for i = 10:1:65
x(i-9) = i;
theta = i;
tspan = linspace(0,1000,1000);
V = 60;
Vx = 60*cosd(theta);
Vy = 60*sind(theta);
options.Events = @event_func;
[t,f,te,fe,ie] = ode45(@(t,f) eqs_of_motion(t,f),tspan,[0 0 Vx Vy],options);
if fe(:,2) > 25
x(i-9) = x(i-9);
y(i-9) = fe(:,2);
else fe(:,2) <=25
x(i-9) = 0;
y(i-9) = 0;
end
end
Unrecognized function or variable 'eqs_of_motion'.

Error in solution>@(t,f)eqs_of_motion(t,f) (line 12)
[t,f,te,fe,ie] = ode45(@(t,f) eqs_of_motion(t,f),tspan,[0 0 Vx Vy],options);

Error in odearguments (line 92)
f0 = ode(t0,y0,args{:}); % ODE15I sets args{1} to yp0.

Error in ode45 (line 104)
odearguments(odeIsFuncHandle,odeTreatAsMFile, solver_name, ode, tspan, y0, options, varargin);
for i = 1:56
if x(i) == 0
x(i) = []
end
end

Answers (2)

Torsten
Torsten on 10 Mar 2024
Moved: Torsten on 10 Mar 2024
Use
x(x==0) = [];
instead of
for i = 1:56
if x(i) == 0
x(i) = []
end
end
The length of the x-vector will become shorter than 56 in the course of the loop such that x(56), e.g., will no longer exist when i = 56. This causes an access error.

Walter Roberson
Walter Roberson on 10 Mar 2024
@Torsten's recommendation of x(x==0) = [] is the best. But alternately,
for i = 56:-1:1
if x(i) == 0
x(i) = []
end
end
Each time you delete an entry, the following entries "fall down" to fill the hole. If you are looping forward 1:56 then if even one entry gets deleted then x(56) will no longer exist and you get the error. If you loop backwards then you do not encounter the same problem.

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!