Incorrect results for subtraction despite working for other use cases.

3 views (last 30 days)
function [S_i, S_o, magnification, FOV] = sequential_Imaging(S_init, H_init, gaps, f)
% Imaging achieved via a sequence of thin lens
S_o(1) = S_init;
H_o = H_init;
for i = 1:length(f)
S_i(i) = 1/(1/f(i) - 1/S_o(i) );
H_i(i) = (S_i(i)/S_o(i))*H_o;
% S_o(i+1) = gaps(i) - S_i(i);
H_o = H_i(i);
end
magnification = S_i/S_init;
FOV = 2*(180/pi)*atan(H_i/S_i);
end
clear
object_height = 0;
object_distance = 40;
focal_lengths = [12 18 20];
segments_of_free_space = [object_distance %40 %30]
[image_distance, object_distance, M, FOV] = sequential_Imaging(object_distance, object_height, segments_of_free_space, focal_lengths);
image_distance
object_distance
The commented code in the for loop is giving rise to an error in my calculations. When I run the code i expect the outputs to be
40 - 17.1429 = 22.8751
30 - 84.7059 = -54.7059
but for some reason when asked to compute (30-84.7059) i keep getting -44.7059 instead of -54.7059. What am I doing wrong?

Answers (1)

Torsten
Torsten on 1 Aug 2025
Edited: Torsten on 1 Aug 2025
"segments_of_free_space" and "focal_lengths" (or "f" and "gaps") must have the same number of elements because you reference gaps(i) for 1 <= i <= length(f).
for i = 1:length(f)
S_i(i) = 1/(1/f(i) - 1/S_o(i) );
H_i(i) = (S_i(i)/S_o(i))*H_o;
% S_o(i+1) = gaps(i) - S_i(i);
H_o = H_i(i);
end
  1 Comment
Aron
Aron on 1 Aug 2025
Edited: Aron on 1 Aug 2025
Hi thanks for commenting. I managed to figure this out after a little more trial and error. all i had to do was change the index of gaps in the for loop to i+1.
function [S_i, H_i, magnification, FOV] = sequential_Imaging(S_init, H_init, gaps, f)
% Imaging achieved via a sequence of thin lens
S_o = gaps(1);
H_o = H_init;
for i = 1:length(f)
S_i(i) = 1/(1/f(i) - 1/S_o );
H_i(i) = (S_i(i)/S_o)*H_o;
if i<length(f)
S_o = gaps(i+1) - S_i(i)
H_o = H_i(i);
end
end
magnification = S_i/S_init;
FOV = 2*(180/pi)*atan(H_i/S_i);
end
%% Actual script
clear
object_height = 0;
object_distance = 40;
focal_lengths = [12 18 20];
segments_of_free_space = [object_distance 40 30];
[image_distance, image_height, M, FOV] = sequential_Imaging(object_distance, object_height, segments_of_free_space, focal_lengths);
S_o = 22.8571
S_o = -54.7059
image_distance
image_distance = 1×3
17.1429 84.7059 14.6457
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!