Monday, May 11, 2009

Matlab: Matrix Indexing

OP here.


Q:

Suppose I have a 3D matrix A:

A(:,:,1) =
[0.1, 0.2, 0;
0.2, 0, 0;
0.6, 0.4, 0]

A(:,:,2) =
[0.2, 0.7, 0;
0.3, 0.8, 0;
0.1, 0, 0]


I want to find, for each row, the element before the first occurrence of zero and subtract it from 1. The outcome should look like this:

B(:,:,1) =
[0.1, 0.8, 0;
0.8, 0, 0;
0.4, 0.6, 0]

B(:,:,2) =
[0.2,0.3,0;
0.3, 0.2, 0;
0.9, 0, 0]



A1:

% location of first occurrence of zero in each row.
z = cumsum(A == 0,2) == 1;
% the element before it.
y = circshift(z,[0,-1]);
B = A;
B(y) = 1-B(y);


A2 (a beautiful solution):

% convolution along columns.
y = convn(logical(A),[-1 1],'same') > 0;
B = A;
B(y) = 1-B(y);

No comments: