3

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.

mohammad rezza
  • 324
  • 1
  • 3
  • 17
  • 2
    The duplicate explains why this error happens (`theta*10+901` might not be an exact integer due to floating point accuracy). For how to fix this, don't use the answer by Ahmed AEK, which you accepted, please. It works in this case, but might trip you over in the future, as it doesn't readily extend to a general case. Instead, read the answer by Cris Luengo, which is a general solution (and well explained + not difficult). – Adriaan Mar 24 '23 at 14:14

2 Answers2

3

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.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
1

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.

Ahmed AEK
  • 8,584
  • 2
  • 7
  • 23
  • 1
    Rounding is a quick and dirty fix here, which might not work in the general case (e.g. rounding two different numbers to the same integer). Better would be to define a separate indexing array, as Cris Luengo does in [his answer](https://stackoverflow.com/a/75834528/5211833). – Adriaan Mar 24 '23 at 13:58