You have to set the correct size of W before you do the loop. So instead of W=[]; you should use something like:
W=zeros(K+1,n);
Also you can then remove the W(1,:)=0; line
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!