error - "Attempted to access w(0.000542549); index must be a positive integer or logical."

4 Ansichten (letzte 30 Tage)
I am writing a code to find the gain of a tranversal filter. I am getting the error - "Attempted to access w(0.000542549); index must be a positive integer or logical." The code is shown below:
del_L = 10;
del_Lambda = 1550*10^(-9);
D = 35;
rho_D = D*del_L*del_Lambda
% n_Lambda = input('Enter the refractive index of the fiber core');
n_Lambda = 1.46;
c = 3*10^8;%Speed of light
rho_d = (del_L*n_Lambda)/c;
a = rho_d+rho_D
for f=8:0.1:12.5
w = abs(2*3.14*f)
H0 = mod(1+cos(w(rho_d+rho_D)),0)/2
end
Please help!

Akzeptierte Antwort

Robert
Robert am 21 Okt. 2015
Just before your final end statement you have the line
H0 = mod(1+cos(w(rho_d+rho_D)),0)/2
The error occurs when MATLAB tries to index into the variable w in your statement w(rho_d+rho_D). I bet you didn't mean to index into w. If you meant to multiply the two expressions, you need an asterisk.
H0 = mod(1+cos(w*(rho_d+rho_D)),0)/2
  2 Kommentare
Rohith Ramaiah
Rohith Ramaiah am 21 Okt. 2015
Thank you for the answer. How can I express the equation: H(w) = 1+cos[w(rho_D+rho_d)]/2 with w *(omega) running through the frequencies 8-12.5 Ghz.
Robert
Robert am 21 Okt. 2015
MATLAB is great at this kind of computation (among others). Instead of the for loop, you can vectorize your computation (a MATLAB term referring to exactly what we are doing: accelerating code by trading loops for vector math).
Instead of assigning f as the iterator of the loop, let's make it the whole loop vector.
f = 8:0.1:12.5; % a row vector of all your f values
Then we can operate on the vector. You have to be careful when you have multiple vectors, but in your case, all your other values are scalars so the code is pretty foolproof.
w = abs(2*pi*f); % just like before, but with MATLAB's built-in value for pi
H = 1 + cos(w*(rho_D+rho_d))/2; % or cosd for inputs in degrees
Just a heads up: did you mean (1 + cos(...) )/2 as in your original code or 1 + cos(...)/2 as in your comment?

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by