MATLAB: 3D matrix index out of bounds problem

exceeds matrx dimensions

I have the following scenario:
lx=101; ly = 101;
opposites = [1, 4, 5, 2, 3, 8, 9, 6, 7];
fIni = zeros(lx, ly, 9);
f = zeros(lx,ly,9);
walls = ones(lx,ly);
walls(2:ly-1,2:lx-1) = 0; % the walls matrix now has ones along the "walls" and zeros in the middle
walls = find(walls); % walls now contains a vector with the non zero indices, i.e. the "walls"
for i=1:9
f(walls,i) = fIni(walls,opposites(i));
end
This generates the error message:
Index exceeds matrix dimensions.
Error in myTest (line 63)
f(walls,i) = fIni(walls,opposites(i));
The length of opposites is 9 so there should be no dimension mismatch there, using the walls vector to address both rows and columns seems to work fine since I can write f(walls,1) = 0; without any error messages… So where does this go wrong?
Appreciate all the help i can get 🙂

Best Answer

fIni = zeros(lx*ly, 9);
f = zeros(lx*ly,9);
walls = true(lx,ly);
walls(2:ly-1,2:lx-1) = false;
fwalls(walls,:)=fIni(walls,opposites);
fwalls=reshape(fwalls,lx,ly,[]);
Related Question