Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB error in "for" loop: Array indices must be positive integers or logical values [duplicate]

Tags:

matlab

in the following example, I get error when I want to simulate.

R1=(2e-3)*[0 3 0
    0 2 0
    0 1 0
    0 0 0
    0 -1 0
    0 -2 0
    0 -3 0];

R2=(5e-3)*[0 3 0
    0 2 0
    0 1 0
    0 0 0
    0 -1 0
    0 -2 0
    0 -3 0];

R3=(5e-3)*[0 3+0.3*randn() 0
    0 2+0.3*randn() 0
    0 1+0.3*randn() 0
    0 0+0.3*randn() 0
    0 -1+0.3*randn() 0
    0 -2+0.3*randn() 0
    0 -3+0.3*randn() 0];
hold on
phases=[0 0 0 0 0 0 0];
phi=90;
AF_tot=zeros(1,1802);
for theta=-90:0.1:90
    AF_tot(theta*10+901)=Array_beam_cal(R3,phases,theta,phi);
end
global_theta=-90:0.1:90;
plot(global_theta,AF_tot,'linewidth',1.5);
xlabel('theta(degree)');
ylabel('array factor');

Error is:

Array indices must be positive integers or logical values.

Noticing my example code, all indexes in "AF_tot(theta*10+901)" are positive. If I change part of previous code to following one:

AF_tot=zeros(1,181);
    for theta=-90:90
        AF_tot(theta+91)=Array_beam_cal(R3,phases,theta,phi);
    end

error does not occur.

like image 280
mohammad rezza Avatar asked Dec 16 '25 12:12

mohammad rezza


2 Answers

Instead of using theta as the loop variable and index with with, which you can’t do because it’s not an integer sequence, use a separate index:

theta = -90:0.1:90;
AF_tot = zeros(size(theta));
for ii = 1:numel(theta)
    AF_tot(ii) = … theta(ii) …;
end
plot(global_theta,AF_tot,…);

Note a few simplifications with this approach: I didn’t need to figure out the number 1802, and I didn’t have to figure out how to map theta values to indices. I also won’t need to update that value and that mapping if I change the theta values. Simpler code is less likely to have bugs, is easier to read, and is easier to maintain.

like image 176
Cris Luengo Avatar answered Dec 19 '25 06:12

Cris Luengo


floating point maths isn't always accurate, it may result in -89.000001 which causes this error.

just round the numbers to avoid this.

AF_tot(round(theta*10+901))=Array_beam_cal(R3,phases,theta,phi);

side note: AF_tot should be 1x1801 not 1x1802.

like image 22
Ahmed AEK Avatar answered Dec 19 '25 05:12

Ahmed AEK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!