Get elements of a matrix that are greater than sum of their two indices in row major order
이전 댓글 표시
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.
댓글 수: 1
Stephen23
2015년 5월 23일
An interesting coincidence:
답변 (2개)
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
2015년 5월 23일
Jan
2015년 5월 24일
@Alisha: Please explain, which version is not working properly and which problem you observe.
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
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
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!