How do I solve this error?
2 views (last 30 days)
Show older comments
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!
0 Comments
Accepted Answer
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.
More Answers (0)
See Also
Categories
Find more on Denoising and Compression in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!