user3618451
user3618451

Reputation: 325

Getting row and column numbers of valid elements in a matrix

I have a 3x3 matrix, populated with NaN and values of a variable:

NaN 7   NaN
5   NaN 0
NaN NaN 4

matrix = [NaN 7 NaN; 5 NaN 0; NaN NaN 4]

I would like to get the row and column numbers of non-NaN cells and put them in a matrix together with the value of the variable. That is, I would like to obtain the following matrix:

row col value
1   2   7
2   1   5
2   3   0
3   3   4

want = [1   2   7; 2   1   5; 2   3   0; 3   3   4]

Any help would be highly appreciated.

Upvotes: 0

Views: 97

Answers (3)

knedlsepp
knedlsepp

Reputation: 6084

If you don't mind the ordering of the rows, you can use a simplified version of Luis Mendo's answer:

[row, col] = find(~isnan(matrix));
result = [row(:), col(:), matrix(~isnan(matrix))];

Which will result in:

 2     1     5
 1     2     7
 2     3     0
 3     3     4

Upvotes: 0

Luis Mendo
Luis Mendo

Reputation: 112659

This can be done without loops:

[jj, ii, kk] = find((~isnan(matrix).*(reshape(1:numel(matrix), size(matrix)))).');
result = [ii jj matrix(kk)];

The trick is to multiply ~isnan(matrix) by a matrix of indices so that the third output of find gives the linear index of non-NaN entries. The transpose is needed to have the same order as in the question.

Upvotes: 1

ha9u63a7
ha9u63a7

Reputation: 6804

The following should work!

[p,q]=find(~isnan(matrix)) % Loops through matrix to find indices

want = zeros(numel(p),3) % three columns you need with same number of rows as p

for i=1:numel(p)
    want[i,:] = [p(i) q(i) matrix(p(i), matrix(i))]
end

Should give you the correct result which is:

 2     1     5
 1     2     7
 2     3     0
 3     3     4

Upvotes: 0

Related Questions