MATLAB: Reference to a cleared variable seg_result.

reference to a cleared variable

Hi friends After I runned the following program:
clear all;
clc;
close all;
load('result_3.mat');
load('mouse3.mat');
load('P.mat');
load('b.mat');
Evalue = b;
Evector = P;
showcs3(mouse);
hold on;
h=[]; h2=[];save_b=[];
location = newkidney;
location(:,3) = round(location(:,3));
for k=1:3
[faces,tnorm]=MyRobustCrust(location);
N=ASM_GetContourNormals3D(location,faces);
[gt,dgt]=ASM_getProfileAndDerivatives3D(mouse,location,N,5);
move=zeros(length(location),3);
[C1,I1]=max(abs(dgt));
xi=location(:,1)-N(:,1).*(I1-6)';
yi=location(:,2)-N(:,2).*(I1-6)';
zi=location(:,3)-N(:,3).*(I1-6)';
move=[xi,yi,zi];
if(ishandle(h2)), delete(h2); end
pause(0.5)
h2=plot3(move(:,1),move(:,2),move(:,3),'.r'); drawnow('expose');
move_pos=[move(:,1);move(:,2);move(:,3)];
location1=[location(:,1);location(:,2);location(:,3)];
b =Evector'*(move_pos-location1);
maxb=3*sqrt(Evalue');
b=max(min(b,maxb),-maxb)
xy_search(:,k) = location1 + Evector*b;
save_b=[save_b,b];
pos=[];
pos=xy_search(:,k);
m=length(N);
location=[pos(1:m,1),pos(m+1:2*m,1),pos(2*m+1:3*m,1)];
if(ishandle(h)), delete(h); end
pause(0.5)
h=plot3(location(:,1),location(:,2),location(:,3),'.g');drawnow('expose');
pause(0.5)
end
if(ishandle(h2)), delete(h2); end
figure;
I = load('3.txt');
plot3(I(:,1),I(:,2),I(:,3),'.b');
hold on;
plot3(location(:,1),location(:,2),location(:,3),'.g');
for l = 153:1:227
figure;
QQ = mouse(:,:,l);
imshow(QQ,[]);
hold on;
seg_result(:, 3) = round(seg_result(:, 3));
for i = 1:1:1519
if seg_result(i, 3) == l
plot(seg_result(i, 2),seg_result(i, 1),'.');
hold on;
end
end
for j = 1:1:1510
if I(j, 3) == l
plot(I(j, 2),I(j, 1),'.r');
end
end
end
I saw an error:
Reference to a cleared variable seg_result.
Error in segment (line 70)
seg_result(:, 3) = round(seg_result(:, 3));
If you know how to deal with it,please help me.Thank you!

Best Answer

This is a classic example of why it is a very bad idea to call load without assigning its output to a variable. It also shows why using clear is pointless and confusing, even though beginners love to use it at the top of every script!
Explanation
Look at your code: on line 70 your use the variable seg_result. But where is this defined? Nowhere. There is no line in your code which defines this variable. Possibly it is (or was) the name of a variable imported by load, but which load ? Because you have chosen to load directly into the workspace we have no way of checking or knowing where this variable comes from. This is why load-ing directly into the workspace is a bad idea, because it makes understanding the code impossible, and impossible to know what variables come from which files. Variables can even be overwritten and it is impossible to know this.
This is a very bad programming style.
Solution
Learn to write code more robustly. Call load with an output argument (a structure), and use that structure:
S = load(...)
...
S.seg_result