echo on
% Assume you have a vector
x = [0,1,0,6,0,5,0,0,2]
% with relational operators you can easily find positions
l = find(x ~= 0)
% and the values
v = x(l)
% and you get your logical result with 1 at positions 1, 2, 5 and 6
r = logical(zeros(size(x)));
r(v) = 1
% For a single vector, this was a little bit to complicated, because one
% could just write
r = logical(zeros(size(x)));
r(x(x~=0)) = 1
% which gives exactly the same.
% Now assume we would like to do the same in rows of a matrix.
% So, here is some test matrix
X = [0,1,4,0; 2,3,0,0; 0,0,0,0; 1,0,0,3]
% and again with find one can locate the indices of values which are
% different from zero
L = X ~= 0
[ir,ic] = find(L) % ir for rows, ic for columns
% and its values
iv = X(L)
% If you now try
W = zeros(size(X));
W(ir,iv) = 1
% you get something which is clearly wrong!
% For a correct result, you must return to the single index
ind = sub2ind(size(X),ir,iv)
R = zeros(size(X));
R(ind) = 1
% which is the correct result.
% Does one want to put this in 3-D, then put it directly in place
n = size(X,1);
R3 = zeros(n,1,n) % is an (n x 1 x n)-array
i3 = sub2ind(size(R3),ir,ones(size(ir)),iv)
R3(i3) = 1
% and then you can replicate things
R3 = repmat(R3,[1,n,1])
% to get a (n x n x n)-array.
%
% Good luck, WiKe
echo off