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

4 ビュー (過去 30 日間)
Alisha Ali
Alisha Ali 2015 年 5 月 23 日
コメント済み: Jan 2015 年 5 月 24 日
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.

回答 (2 件)

Andrei Bobrov
Andrei Bobrov 2015 年 5 月 23 日
編集済み: Andrei Bobrov 2015 年 5 月 23 日
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(:)];
  2 件のコメント
Alisha Ali
Alisha Ali 2015 年 5 月 23 日
doesn't work correctly for [1 4; 5 2; 6 0]
Jan
Jan 2015 年 5 月 24 日
@Alisha: Please explain, which version is not working properly and which problem you observe.

サインインしてコメントする。


Stephen23
Stephen23 2015 年 5 月 23 日
編集済み: Stephen23 2015 年 5 月 23 日
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
  1 件のコメント
Stephen23
Stephen23 2015 年 5 月 23 日
編集済み: Stephen23 2015 年 5 月 23 日
Using the sample data:
>> A = [1 4; 5 2; 6 0]
A =
1 4
5 2
6 0
>> large_elements(A)
ans =
1 2
2 1
3 1

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by