Why do I get Array indices must be positive integers or logical values?

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

Answers (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 Comments

But what do I do when I need my t to have the values [0 tl]?
You mean something like this?
t = 0:360;
% x and y are functions of t
x = cosd(t);
y = sind(t);
plot(x, y) % no need to specify x(t) or y(t)
axis square % make the axes square rather than rectangular
hold on % let me plot something else on this same axes
plot(x(t == 0), y(t == 0), 'rx') % x marks the starting spot
My code looks like this now:
alfa = pi/6;
v0 = 300;
[h,dx] = flyrange(v0,alfa);
function [h,dx] = flyrange(v0,alfa)
g = 9.81;
% ax = 0;
% ay = g;
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:t]
t = [0:tl]
x(n) = a.*t;
y(n) = (-1/2).*g.*t.^(2) + b.*t;
end
plot(x,y)
end
And now Matlab has this error:
Unrecognized function or variable 'x'.
Error in Matlab>flyrange (line 26)
plot(x,y)
Error in Matlab (line 8)
[h,dx] = flyrange(v0,alfa);
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.
Thank you for your help! I get it know what I did wrong and I got the code go thru without any problems! :)

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 1 Feb 2021

Commented:

on 1 Feb 2021

Community Treasure Hunt

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

Start Hunting!