Sammy Ofer
Sammy Ofer

Reputation: 11

Why is MATLAB giving me an error that states that "index in position 2 is invalid"?

This code seems like it should be simple, but for some reason I keep getting this error: "Index in position 2 is invalid. Array indices must be positive integers or logical values."

It refers to these lines:

Vr = (V*R)/(sqrt((R^2)+(w*L-(1/(w*C))^2)));
VR(1,i) = Vr;

I've tried checking if I entered the equation wrong or if I have to save certain values as integers but nothing seems to work. Any advice would be greatly appreciated.

Here's the full code if you need:

disp('Please enter Vo in volts, R in kiloOhms, L in miliHenries, and C in picoFarads');
input = input('Enter values as single matrix.  ');

V = input(1,1);
R = input(1,2);
L = input(1,3);
C = input(1,4);

VR = zeros(1,1000);      

for i = 0:1000
    w=i*10*10^-9;
    Vr = (V*R)/(sqrt((R^2)+(w*L-(1/(w*C))^2)));
    VR(1,i) = Vr;
end

Thanks!

Upvotes: 1

Views: 3237

Answers (1)

smttsp
smttsp

Reputation: 4191

Your for loop starts from zero but Matlab is 1-indexed language.

VR = zeros(1,1000);      

for i = 1:1000 % <- Mistake was here, change zero to one
    w=i*10*10^-9;
    Vr = (V*R)/(sqrt((R^2)+(w*L-(1/(w*C))^2)));
    VR(1,i) = Vr;
end

Upvotes: 1

Related Questions