MATLAB Answers

Why am I receiving the error "Array indices must be positive integers or logical values."?

17 views (last 30 days)
Deniz Duran
Deniz Duran on 19 Sep 2021
Commented: Deniz Duran on 20 Sep 2021 at 19:09
I am trying to graph the current distributions of a dipole antenna. I keep getting the error "Array indices must be positive integers or logical values." I want to obtain the current distributions for l=0.25λ,0.5λ,0.75λ,λ,1.25λ,1.5λ,1.75λ and 2λ. Here is my code:
z = 0:0.25:2;
l = 0.5; %(change l for desired value)
k = 2*pi;
I = zeros(1,length(z));
I0 = 1;
for i = 0<=z<=l/2;
I(i) = I0*sin(k(l/2 - z)); % Define I(z)
end
for i = -l/2<=z<=0;
I(i) = I0*sin(k(l/2 + z));
end
figure(1)
plot(z,I); %Plot Rectangular
title('Current Distribution');
xlabel('Coordinate z(lambda)');
ylabel('Current, I');

Accepted Answer

the cyclist
the cyclist on 20 Sep 2021 at 19:02
Here is a completely different tack, that I think is less confusing because you just defining the function I(z) more naturally as you have it, and don't have to worry about the indexing problem
% Define parameters
l = 0.5; %(change l for desired value)
k0 = 2*pi;
I0 = 1;
% Define plotting range for z
z = -l/2 : l/100 : l/2;
% Define anonymous function I(z)
I = @(z) (z>=0) .* I0.*sin(k0*(l/2-z)) + (z<0) .* I0.*sin(k0*(l/2+z));
% Plot
figure
plot(z,I(z))
title('Current Distribution');
xlabel('Coordinate z(lambda)');
ylabel('Current, I');
  1 Comment
Deniz Duran
Deniz Duran on 20 Sep 2021 at 19:09
It is not a homework Sir. I am just trying to implement the theory I learn in class to Matlab to both understand the theory better and try learning Matlab as I go along. Your code makes so much sense! Thank you for contrubuting to my learning journey.

Sign in to comment.

More Answers (2)

the cyclist
the cyclist on 19 Sep 2021 at 21:30
Edited: the cyclist on 19 Sep 2021 at 21:31
You have at least two problems with your code. First, you need an explicit multiplication sign in these lines:
I(i) = I0*sin(k*(l/2 - z)); % Added *
and
I(i) = I0*sin(k*(l/2 + z));
Second, your for loop is ill-defined, as probably does not do what you intend. You cannot specify a range of z values as you have here:
for i = 0<=z<=l/2;
Instead, you need something more like
for i = z*l % I think this maybe be what you intend? Steps are fractions of lambda (l)
In this syntax, i is going to loop over the values of the vector z*l.
  2 Comments
the cyclist
the cyclist on 20 Sep 2021 at 18:53
OK, so this exposes yet another error that I had missed the first time, which is that you are using a looping variable that takes on values of zero and fractions, and then you try to use those as an index into a vector. That makes no sense (as the link @Image Analyst shared explains).
I'll add another answer in a bit.
Out of curiosity, is this a homework assignment?

Sign in to comment.


Tags

Community Treasure Hunt

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

Start Hunting!

Translated by