Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
727 views
in Technique[技术] by (71.8m points)

matlab - Filter matrix rows depending on values in a second matrix

Given a 2x3 matrix x and a 4x2 matrix y, I'd like to use each row of y to index into x. If the value in x is not equal to -1 I'd like to remove that row from y. Here's an example that does what I'd like, except I'd like to do it in a fast, simple way without a loop.

x = [1, 2, 3; -1, 2, -1];
y = [1, 1; 1, 3; 2, 1; 2, 3];

for i=size(y,1):-1:1
   if x(y(i,1), y(i,2)) ~= -1
      y(i,:) = [];
   end
end

This results in:

y =

     2     1
     2     3
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A raw approach to what sub2ind follows (as used by this pretty nice-looking solution posted by Luis) inherently would be this -

y = y(x((y(:,2)-1)*size(x,1)+y(:,1))==-1,:)

Benchmarking

Benchmarking Code

N = 5000;
num_runs = 10000;

x = round(rand(N,N).*2)-1;
y = zeros(N,2);
y(:,1) = randi(size(x,1),N,1);
y(:,2) = randi(size(x,2),N,1);

disp('----------------- With sub2ind ')
tic
for k = 1:num_runs
    y1 = y(x(sub2ind(size(x), y(:,1), y(:,2)))==-1,:);
end
toc,clear y1

disp('----------- With raw version of sub2ind ')
tic
for k = 1:num_runs
    y2 = y(x((y(:,2)-1)*size(x,1)+y(:,1))==-1,:);
end
toc

Results

----------------- With sub2ind 
Elapsed time is 4.095730 seconds.
----------- With raw version of sub2ind 
Elapsed time is 2.405532 seconds.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...