MATLAB: Set output when index is out of bounds

errorindexMATLAB

Hi all,
I have 2 matrices A and B. A has dimensions (n,m,2) and B has dimensions (p,m).
A has been constructed (during execution) in such a way that that the elements in A(n,m,1) are indices of B corresponding to the first dimension (p) and A(n,m,2) has coefficients.
For the purpose of my calculation i need to compute quantities like B(A(n,m,1),m)*A(n,m,2).
Here, I am facing the issue that some elements in A(n,m,1) are greater than p but in all such cases A(n,m,2) is zero. During execution I get the index exceeds dimensions error but I don't actually care about it as whenever the index is out of bounds the result gets multiplied by 0.
So, I want to know if there is a way to suppress this error or to assign an arbitrary output when the index exceeds the dimensions?
ps. I have tried setting the values of A(n,m,1) to 1 when A(n,m,2) is 0 but this too causes issues because for certain inputs to my code, B can be an empty matrix (in such cases A(n,m,2)=0 for all m,n)

Best Answer

mask = A(:,:,1) <= p;
mask1 = cat3(mask, false(size(A,1),size(A,2)));
mask2 = mask1(:,:,[2 1]);
result = B(A(mask1)) .* A(mask2));