MATLAB: Do I receive a segmentation violation when I allocate memory differently for a pre-existing vector in MATLAB 6.5 (R13)

allocatefaultlinuxMATLABmemorysegmentationunixvectorviolation

Why do I receive a segmentation violation when I allocate memory differently for a pre-existing vector in MATLAB 6.5 (R13)?
I have an existing 4-by-1 vector, which I defined by concatenating three matrices: a 2-by-1 matrix, a 1-by-1 matrix, and a 1-by-1 matrix. Later in my code, I define the matrix by concatenating three matrices again: a 1-by-1 matrix, a 1-by-1 matrix, and a 2-by-1 matrix.
A=zeros(4,4,2);
A(:,:,1)=[4 3 2 1;
3 3 2 1;
2 2 2 1;
1 1 1 1];
for kk=1:2,
x=A(kk+1:4,kk,kk)
t=sqrt(x'*x)
%w is the 4X1 matrix
w=[zeros(kk,1)
A(kk+1,kk,kk)+sign(A(kk+1,kk,kk))*sqrt(t)
A(kk+2:4,kk,kk)]
end
Register State:
g0 = 00000000 o0 = 40080000 l0 = ffbeb350 i0 = 00000003
g1 = 00000001 o1 = 00000000 l1 = 00000001 i1 = ffbeb34c
g2 = ff24a1a8 o2 = 00000000 l2 = ffbeb34c i2 = fec740c0
g3 = 000a9414 o3 = 0094e818 l3 = 00000003 i3 = 00000000
g4 = 0013e208 o4 = ff278ba8 l4 = 0094e818 i4 = 00000000
[snip]
Stack Trace:
[0] libmwm_dispatcher.so:inGetDispatchType(0x40080000, 0, 0, 0x0094e818) + 0 bytes (leaf)
[1] libmwm_interpreter.so:inSqBrkDispatchRules(3, 0xffbeb34c,0xfec740c0, 0) + 96 bytes
[2] libmx.so:mxCatenateDispatch(1, 0, 0x0094ef20, 0xffbeb34c) + 296 bytes
[3] libmwm_interpreter.so:inVertcatFcn(1, 0xffbeb344, 3, 0xffbeb34c) + 132 bytes
[4] libmwm_interpreter.so:inJitCallMatlabFunctionWithType(0xfebcae68, 0xffbecf10, 1, 0xffbeb34c) + 140 bytes
[5] libmwm_interpreter.so:accelExec(0xfec05c30, 57, 0xfec740c0, 0xffbeb3cd) + 11444 bytes
[6] libmwm_interpreter.so:inAccel(1302536, 0xfec97c20, 0xfec97c10, 0xfec7bc0c) + 16 bytes
[7] libmwm_interpreter.so:bool inExecuteHotSegment(_inJitAccelInfo*,opcodes*,int*)(736, 0xffbeb5cc, 0xfec7b7bc, 0xfec96620) + 712 bytes
[snip]

Best Answer

This bug has been fixed for Release 14 (R14). For previous releases, please read below for any possible workarounds:
This has been verified as a bug in MATLAB 6.5 (R13).
You are receiving this error because of the way memory is allocated in MATLAB under a UNIX system.
In the first pass of your FOR-loop, "w" is a combination of a 1-by-1 matrix, a 1-by-1 matrix, and a 2-by-1 matrix.
In the second pass, "w" is instead a combination of a 2-by-1 matrix, a 1-by-1 matrix, and a 1-by-1 matrix.
MATLAB is expecting the matrix to be produced as it was before, and when it does not, MATLAB produces the segmentation violation.
The CLEAR function should alleviate this problem since MATLAB will no longer expect "w" to be allocated in a certain way during the second pass of your FOR-loop. Try inserting the following line of code before you set the value for "w":
clear w
Thus, your code should look like this:
A=zeros(4,4,2);
A(:,:,1)=[4 3 2 1;
3 3 2 1;
2 2 2 1;
1 1 1 1];
for kk=1:2,
x=A(kk+1:4,kk,kk)
t=sqrt(x'*x)
clear w
w=[zeros(kk,1)
A(kk+1,kk,kk)+sign(A(kk+1,kk,kk))*sqrt(t)
A(kk+2:4,kk,kk)]
end