How do I solve this error?

2 ビュー (過去 30 日間)
Axelina Lindgren
Axelina Lindgren 2021 年 4 月 25 日
コメント済み: Axelina Lindgren 2021 年 4 月 25 日
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!

採用された回答

Jan
Jan 2021 年 4 月 25 日
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 件のコメント
Axelina Lindgren
Axelina Lindgren 2021 年 4 月 25 日
Thank you so much for your help! Works perfectly now.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeDenoising and Compression についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by