根据第二个矩阵中的值过滤矩阵行(Filter matrix rows depending on values in a second matrix)

编程入门 行业动态 更新时间:2024-10-26 13:18:43
根据第二个矩阵中的值过滤矩阵行(Filter matrix rows depending on values in a second matrix)

给定2x3矩阵x和4x2矩阵y ,我想使用y每一行来索引x 。 如果x的值不等于-1我想从y删除该行。 这是一个做我想做的事情的例子,除了我想在没有循环的情况下以快速,简单的方式做到这一点。

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

这导致:

y = 2 1 2 3

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

最满意答案

对于sub2ind遵循的原始方法(由Luis发布的这个相当漂亮的解决方案使用)本身就是这样的 -

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

标杆

基准代码

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

结果

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

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.

更多推荐

本文发布于:2023-07-31 02:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340392.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:矩阵   第二个   Filter   matrix   depending

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!