Why do I get Array indices must be positive integers or logical values?
1 回表示 (過去 30 日間)
古いコメントを表示
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 件のコメント
回答 (1 件)
Steven Lord
2021 年 2 月 1 日
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 件のコメント
Steven Lord
2021 年 2 月 1 日
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.
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

