質問

I have the square matrix with elements, that can take values from {-1, 0, 1}. I know that there is only 1 element equals to -1 in every row (except the first row, where are only non-negative elements).

Let n be the size of the matrix. So, I want to assign to every index i from [2, n] the position of -1 in i-th row from matrix.

How can I do this without using a for or while loop?

役に立ちましたか?

解決

t = matrix==-1;
[~, pos] = max(t,[],2); %// position of first -1 within each row.
pos = pos .* any(t,2); %// give 0 for rows that don't contain any -1 value

pos(k) gives the position of the (first) -1 value within row k, or 0 if there isn't any -1 value in that row.

Example:

matrix =

     1     0     0     1
     0     1    -1     1
     0     1     1    -1
     0     0     1    -1

gives

pos =

     0
     3
     4
     4
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top