Why do I get Array indices must be positive integers or logical values?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
What am I doing wrong? I seem to get the error what ever I try. Can someone help, please :)
alfa = pi/6;
v0 = 300;
[h,dx] = flyrange(v0,alfa);
function [h,dx] = flyrange(v0,alfa)
g = 9.81;
a = v0.*cos(alfa);%a = v0x
b = v0.*sin(alfa);%b = v0y
tn = b./g;
tl = 2.*tn;
t = [0:tl];
h = (-1/2).*g.*tn.^(2) + b.*tn;
dx = a.*tl;
for n = [1:tl];
x(n) = a.*t;
y(n) = (-1/2).*g.*t.^(2) + b.*t;
end
plot(x(t),y(t))
end
0 commentaires
Réponses (1)
Steven Lord
le 1 Fév 2021
t = [0:tl];
%snip a bunch of code, none of which changes t
plot(x(t),y(t))
There's no such thing as element 0 of an array in MATLAB. The first element is element 1.
5 commentaires
Steven Lord
le 1 Fév 2021
Here's a piece of your code. I've commented it out so when I run this answer it doesn't try to run this code.
%{
t = [0:tl];
h = (-1/2).*g.*tn.^(2) + b.*tn;
dx = a.*tl;
for n = [1:t]
t = [0:tl]
x(n) = a.*t;
y(n) = (-1/2).*g.*t.^(2) + b.*t;
end
plot(x,y)
%}
Why didn't this work? When you use : and one or more of the operands has more than one element MATLAB will only use the first element. So your loop over n where you're iterating over [1:t] will iterate over the vector 1:t(1) which is 1:0. That vector is empty, so x is never assigned a value.
But you don't need to use a loop here since x and y only depend on a, t, g, and b. Use a vectorized calculation.
% Use sample values for a, b, and g
g = 9.8;
a = 3;
b = 4;
% Also use a sample vector of values for t
t = 0:5;
% Compute x and y for ALL the values of t at once
x = a.*t;
y = (-1/2).*g.*t.^(2) + b.*t;
plot(x, y)
Search the documentation for the term "vectorization" for more info.
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

