Effacer les filtres
Effacer les filtres

How do I solve this error?

3 vues (au cours des 30 derniers jours)
Axelina Lindgren
Axelina Lindgren le 25 Avr 2021
My teacher put in (from what I can tell) an identical code but I can't get it working. Can somebody help me make it work and explain the error?
n1 = 1; %utanför linsen
n2 = 1.5; %i linsen
D = 10; %linsens diameter (cm)
R = D./2; %linsens radie (cm)
d = 10; %fokallängd (cm)
lopt = n1*sqrt(d.^2 + R.^2); %Optiska vägen då strålen inte bryts i linsen
Y = linspace(0, R, 1000);
X = linspace(0, d, 1000);
for ii = 1:length(Y)
L1(:,ii) = sqrt( (d-X).^2 + Y(ii).^2)*n1;
L2(:,ii) = X*n2;
LoptTemp(:,ii) = L1(:,ii) + L2(:,ii);
diff(:,ii) = abs(LoptTemp(:,ii) - lopt);
[difference minIndex(ii)] = min(diff(:,ii));
x_fit(ii) = X(minIndex(ii));
end
figure
plot(x_fit, Y, 'black');
hold on
plot(x_fit.*-1, Y, 'black');
hold on
plot(x_fit, -Y, 'black');
hold on
plot(x_fit.*-1, -Y, 'black');
hold on
ylim([-max(Y)-3, max(Y)+3]);
The error message is:
Conversion to function_handle from double is not possible.
Error in OptikVaglaraUppgift2 (line 75)
LoptTemp(:,ii) = L1(:,ii) + L2(:,ii);
Grateful for help!

Réponse acceptée

Jan
Jan le 25 Avr 2021
The error message means, that the variable LoptTemp has been defined as function handle before.
A pre-allocation solves the problem:
LoptTemp = zeros(length(Y), length(Y));
If you insert this code in a function, the workspace is clean and formerly defined variables to not influence the stability.
  1 commentaire
Axelina Lindgren
Axelina Lindgren le 25 Avr 2021
Thank you so much for your help! Works perfectly now.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Statics and Dynamics dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by