MATLAB Answers

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

조회 수: 32(최근 30일)
Deniz Duran
Deniz Duran 2021년 9월 19일 19:44
댓글: Deniz Duran 2021년 9월 20일 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');

채택된 답변

the cyclist
the cyclist 2021년 9월 20일 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
Deniz Duran
Deniz Duran 2021년 9월 20일 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.

댓글을 달려면 로그인하십시오.

추가 답변(2개)

the cyclist
the cyclist 2021년 9월 19일 21:30
편집: the cyclist 2021년 9월 19일 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
the cyclist
the cyclist 2021년 9월 20일 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?

댓글을 달려면 로그인하십시오.


태그

Community Treasure Hunt

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

Start Hunting!

Translated by