Get elements of a matrix that are greater than sum of their two indices in row major order

4 views (last 30 days)
I'm Writing a function called `large_elements` that takes input an array named `X` that is a matrix or a vector. The function identifies those elements of `X` that are greater than the sum of their two indexes.
For example, if the element `X(2,3)` is `6`, then that element would be identified because `6 > (2 + 3)`. The output of the function gives the indexes(row and column sub) of such elements found in *row-major order*. It is a matrix with exactly two columns. The first column contains the row indexes, while the second column contains the corresponding column indexes.
Here is an example, the statement
indexes = large_elements([1 4; 5 2; 6 0])
should give the output like this:
[1 2; 2 1; 3 1]
If no such element exists,
the function returns an
`empty array`.
I have came up with the following code
function indexes = large_elements(A)
[r c] = size(A);
ind = 1;
for ii = 1:r
for jj = 1:c
if A(ii,jj) > ii + jj
indexes(ind,:) = [ii jj];
ind = ind + 1;
else
indexes = [];
end
end
end
end
But the results are not as expected. Any help would be appreciated.

Answers (2)

Andrei Bobrov
Andrei Bobrov on 23 May 2015
Edited: Andrei Bobrov on 23 May 2015
a = [1 4; 5 2; 6 0]; % your data
n = size(a);
[x,y]=ndgrid(1:n(1),1:n(2));
[ii,jj] = find(a > (x + y));
out = sortrows([ii(:),jj(:)],1);
or
n = size(a);
[ii,jj] = find(a > hankel(2:n(1)+1,(1:n(2))+n(1)));
out = sortrows([ii(:),jj(:)],1);
or
n = size(a)
[ii,jj] = find(a > bsxfun(@plus,(1:n(1))',1:n(2)));
out = sortrows([ii(:),jj(:)],1);
or
n = size(a');
[ii,jj] = find(a' > bsxfun(@plus,(1:n(1))',1:n(2)));
out = [jj(:),ii(:)];

Stephen23
Stephen23 on 23 May 2015
Edited: Stephen23 on 23 May 2015
Solving this kind of problem using two nested loops is very poor use of MATLAB, especially as the output array is growing inside the loops: without any array preallocation this is a slow and very inefficient use of MATLAB. It would be much faster and much simpler using vectorized code, such as this:
function Z = large_elements(X)
[r,c] = size(X);
[r,c] = find(X > bsxfun(@plus, (1:r)', 1:c));
Z = sortrows([r,c]);
which outputs this when run:
>> large_elements(5*ones(3))
ans =
1 1
1 2
1 3
2 1
2 2
3 1

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!