Fatime
Fatime

Reputation: 197

Matlab , matrix operations

I have for example this matrix

A=[ 
  11  15   19   13
  12  16   0    114
  13  17   111  115
  14  18   112  116
  ];

I want to find nonzero elements of two matrix of indices:

i1=[1 3];
i2=[2 4];

The result:

B=A(i2,i1);
B=[12  0
   14 112];

index of matrix in A.

 index=[2 4 12];

So, How to obtain the indices without loop?

Thanks.

Upvotes: 0

Views: 103

Answers (3)

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

There is a one-liner which is not quite readable of course:

index = find(diag(ismember(1:size(A,1), i2))*A*diag(ismember(1:size(A,2), i1)));

or alternatively

index=find(sparse(i2,i2,1,size(A,1),size(A,1))*A*sparse(i1,i1,1,size(A,2),size(A,2)));

and there is more elaborate and readable one:

z=zeros(size(A));
z(i2,i1) = A(i2,i1);
index=find(z);

Note that the first one-liner fails if the matrix contains Inf or NaN values because those values will be multiplied by zero, the second and third methods are more robust in that sense.

Upvotes: 3

Wolfgang Kuehn
Wolfgang Kuehn

Reputation: 12926

Slightly more compact than Bas Swinckels answer:

I=reshape(1:numel(A),size(A));
J=I(i2,i1);
J(~~B)

Upvotes: 1

Bas Swinckels
Bas Swinckels

Reputation: 18488

This is one solution:

% sub2ind does not work, use this hack instead
z = zeros(size(A));
z(i2,i1) = 1
ind = find(z) % get linear indices

%only keep the ones for which A is nonzero
ind = ind(A(ind) ~= 0)

Result:

z =
     0     0     0     0
     1     0     1     0
     0     0     0     0
     1     0     1     0

ind =
     2
     4
    10
    12

ind =
     2
     4
    12

Upvotes: 1

Related Questions