how to find the location of element in matrix?

2 views (last 30 days)
sheno39
sheno39 on 18 Oct 2013
Commented: Azzi Abdelmalek on 28 Oct 2013
my code:
I=[2 3 10 4 6; 1 4 7 5 3; 5 2 8 4 3;8 2 1 7 3;1 9 8 3 4;];
D = padarray(I,[1 1],0,'both');
[x y]=size(D);
m=1;
n=1;
for i=2:x-1
for j=2:y-1
A=[D(i-1,j-1:j+1),D(i,j-1),D(i,j+1),D(i+1,j-1:j+1)];
I1(m,n)=max(A(:));
%[maxval(m,n) index(m,n)]=max(A(:));
n=n+1;
end
m=m+1;
n=1;
end
[tc locatn]=ismember(I1,I);
s=[5,5];
[R C]=ind2sub(s,locatn');
Required output
locatn=[7 11 12 11 17; 3 11 11 11 21; 4 4 12 13 19; 10 10 10 13 19; 10 4 10 15 19]
i got the output as,
locatn=[7 11 12 11 3; 3 11 11 11 21; 4 4 12 4 12; 10 10 10 4 12; 10 4 10 4 12]
can anyone help me to get the required output? how to correct this code?

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 18 Oct 2013
Edited: Andrei Bobrov on 18 Oct 2013
I=[2 3 10 4 6; 1 4 7 5 3; 5 2 8 4 3;8 2 1 7 3;1 9 8 3 4;];
D = padarray(I,[1 1],0,'both');
s = size(I);
N = padarray(reshape(1:numel(I),s),[1 1],0,'both');
pt = [1 1 1;1 0 1;1 1 1] > 0;
s1 = s+2;
out = zeros(s);
for ii=2:s1(1)-1
for jj=2:s1(2)-1
D1 = D(ii-1:ii+1,jj-1:jj+1);
K = N(ii-1:ii+1,jj-1:jj+1);
K = K(pt);
[~,i0] = max(D1(pt));
out(ii-1,jj-1) = K(i0);
end
end
or
I=[2 3 10 4 6; 1 4 7 5 3; 5 2 8 4 3;8 2 1 7 3;1 9 8 3 4;];
D = padarray(I,[1 1],0,'both');
s = size(I);
pt = [1 1 1;1 0 1;1 1 1] > 0;
a = -1:1;
j1 = [1;1;1]*a;
i1 = j1';
i1 = i1(pt);
j1 = j1(pt);
s1 = s+2;
R = zeros(s);
C = zeros(s);
for ii=2:s1(1)-1
for jj=2:s1(2)-1
D1 = D(ii-1:ii+1,jj-1:jj+1);
[~,i0] = max(D1(pt));
R(ii-1,jj-1) = ii + i1(i0) - 1;
C(ii-1,jj-1) = jj + j1(i0) - 1;
end
end
or
I=[2 3 10 4 6; 1 4 7 5 3; 5 2 8 4 3;8 2 1 7 3;1 9 8 3 4;];
Ip = padarray(I,[1 1],0,'both');
s = size(Ip);
s0 = s - 2;
idxi = padarray(reshape(1:numel(I),s0),[1 1],0,'both');
ptr = reshape(bsxfun(@plus,(0:2)',(0:2)*s(1)),1,[]);
p2 = bsxfun(@plus,(1:s0(1))',(0:s0(2)-1)*s(1));
idx = bsxfun(@plus,p2(:),ptr([1:4,6:end]));
[~,ii] = max(Ip(idx),[],2);
s1 = size(idx);
out = reshape(idxi(idx(sub2ind(s1,(1:s1(1))',ii))),s0);
[R,C] = ind2sub(size(out),out);

More Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 18 Oct 2013
Edited: Azzi Abdelmalek on 18 Oct 2013
I think there is an error in your expected locatn, try this
I2=unique(I1(:));
ii=histc(I1(:),I2);
idx1=zeros(size(I));
for k=1:numel(I2)
a=I2(k)
jdx=ismember(I1,a);
j1=find(jdx,ii(k))';
idx=ismember(I,a);
i1=find(idx,ii(k));
i1(end:numel(j1))=i1(end);
idx1(j1)=i1;
end
locatn=idx1
  2 Comments
Azzi Abdelmalek
Azzi Abdelmalek on 28 Oct 2013
If you look for the location of 5 from I1 in the matrix I, there are two 5 in I1, we should find the locations of the two first 5 in I, that's what i1 represent.

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!