MATLAB: I am trying to sum the rows in an array of size 2048×2048 of ‘unit8’ data type.

bmpimagerowssumsum rowsunit8

In the code below, I take the image in the file attached at try to determine the space in which light is not frequent. Toward the bottom of the code at E = , the code sees an error. It says:
Index in position 1 is invalid. Array indices must be positive integers or logical
values.
Error in matlab_ex (line 77)
E = sum(raw_image,2);
Yet, when the same exact line is executed at B =, it runs perfectly. Could there be a reason for this?
clear all;
% change to desired path
path = 'C:\Users\steven.manz\Documents\Shaky Experiment 05_04_2020\distance_experiment\';
res_x = 2048; res_y = 2048; % resolution
A = double(raw_image);
B = sum(raw_image,1);
sum = 0;
for i = 1025:2048
if B(1,i) < 50
sum = sum + 1;
% disp(sum)



end
end
C = find(B<50);
D = C(1, [37:96]);
fprintf('The number of columns on the right half plane \n in which light seen is under threshold is %.1f\n\n',sum)
fprintf('Which happens at\n')
fprintf('column: %d\n',D)
sum = 0;
for i = 1:1024
if B(1,i) < 50
sum = sum + 1;
% disp(sum)
end
end
D = C(1, [1:36]);
fprintf('The number of columns on the right half plane \n in which light seen is under threshold is %.1f\n\n',sum)
fprintf('Which happens at\n')
fprintf('column: %d\n',D)
E = sum(raw_image,2);
sum = 0;
for i = 1025:2048
if E(1,i) < 50
sum = sum + 1;
% disp(sum)
end
end
C = find(E<50);
D = C(1, [37:96]);
fprintf('The number of columns on the top half plane \n in which light seen is under threshold is %.1f',sum)
fprintf('Which happens at\n')
fprintf('column: %d\n',D)
% sum = 0;
% for i = 1025:2048
% if B(1,i) < 50
% sum = sum + 1;
% disp(sum)
% end
% end
%
% fprintf('The number of columns on the bottom half plane \n in which light seen is under threshold is %.1f',sum)

Best Answer

You have defined a variable named 'sum' here
sum = 0; % <====== change its name here and everywhere else
for i = 1025:2048
if B(1,i) < 50
sum = sum + 1;
% disp(sum)
end
end
Therefore, in line
sum(raw_image,2)
MATLAB thinks you are referring to the variable named sum, not the function sum(). Change the name of variable to something else and make the replacement everywhere in the code.