Reputation: 21
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.
Upvotes: 1
Views: 921
Reputation: 3898
One vectorised approch using bsxfun
, find
and ind2sub
A = randi(8,5); %// Your matrix
%// finding sum of the indexes for all elements
indSum = bsxfun(@plus, (1:size(A,1)).', 1:size(A,2));
%// generating a mask of which elements satisfies the given condition (i.e A > indSum)
%// Transposing the mask and finding corresponding indexes
[c,r] = find(bsxfun(@gt, A, indSum).') ;
%// getting the matrix by appending row subs and col subs
out = [r,c]
Results:
Input A:
>> A
A =
4 4 7 2 2
1 3 4 8 3
8 8 2 8 7
8 3 4 5 1
4 1 1 1 1
Output in row-major order:
out =
1 1
1 2
1 3
2 4
3 1
3 2
3 4
4 1
Note: Getting subs in row-major order is tricky here
Also here is your correct loopy approach
[r, c] = size(A);
ind = 0;
indexes = [];
for ii = 1:r
for jj = 1:c
if A(ii,jj) > ii + jj
ind = ind + 1;
indexes(ind,:) = [ii jj];
end
end
end
Upvotes: 0
Reputation: 1982
That is because whenever you encounter an element which is smaller than the sum of its indices you are reinitializing the array to null
. So the output is coming out to be null
. You should not initialize it to null
on the else
condition.
Upvotes: 0