Clear Filters
Clear Filters

How do I solve this error?

2 views (last 30 days)
Axelina Lindgren
Axelina Lindgren on 25 Apr 2021
Commented: Axelina Lindgren on 25 Apr 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!

Accepted Answer

Jan
Jan on 25 Apr 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 Comment
Axelina Lindgren
Axelina Lindgren on 25 Apr 2021
Thank you so much for your help! Works perfectly now.

Sign in to comment.

More Answers (0)

Categories

Find more on Statics and Dynamics in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!