MATLAB: How to vectorize this code

for loopvectorization

for k=1:1:3
for j=1:1:160
for i=1:1:160
for a=1:1:9
%Cover1 in Share1
if enshare1{i,j}(a)==1
enshare1{i,j}(a)=cover1(i,j,k);
else
enshare1{i,j}(a)=cover1(i,j,k)-1;
end
%Cover2 in Share2
if enshare2{i,j}(a)==1
enshare2{i,j}(a)=cover2(i,j,k);
else
enshare2{i,j}(a)=cover2(i,j,k)-1;
end
end
end
end
end
The i,j and k for loops are not in the same way as specified here. I added them so that one need not wonder where those 3 variables came from. I want to vectorize the inner 'a' for loop.
Thanks

Best Answer

isOne = enshare1{i,j} == 1 ;
enshare1{i,j}(:) = cover1(i,j,k)-1 ;
enshare1{i,j}(isOne) = cover1(i,j,k) ;
and same for cover2/share2. The second line above should be
enshare1{i,j}(~isOne) = cover1(i,j,k)-1 ;
but I guess that is is more efficient to skip this indexing and let the 3rd line update relevant elements.
A more efficient but not as clean (up to me) way to do it would be
isOne = enshare1{i,j} == 1 ;
enshare1{i,j} = isOne * cover1(i,j,k) + ~isOne * (cover1(i,j,k)-1) ;