MATLAB:按特定行减去矩阵子集 [英] MATLAB: Subtracting matrix subsets by specific rows

查看:221
本文介绍了MATLAB:按特定行减去矩阵子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我要使用的矩阵子集的一个示例:

Here is an example of a subset of the matrix I would like to use:

1 3 5

1 3 5

2 3 6

1 1 1

3 5 4

5 5 5

8 8 0

这个矩阵实际上是3000 x 3.

This matrix is in fact 3000 x 3.

对于前三行,我希望将这三行中的每一行都减去这三行中的第一行.

For the first 3 rows, I wish to subtract each of these rows with the first row of these three.

对于后三行,我希望用这三行中的第一行减去每行,依此类推.

For the second 3 rows, I wish to subtract each of these rows with the first of these three, and so on.

这样,输出矩阵将如下所示:

As such, the output matrix will look like:

0 0 0

0 0 0

1 0 1

0 -2 -4

0 0 0

2 0 1

5 3 -4

MATLAB中的哪些代码可以为我做到这一点?

What code in MATLAB will do this for me?

推荐答案

一种稍短且矢量化的方式(如果a是您的矩阵):

a slightly shorter and vectorized way will be (if a is your matrix) :

b=a-kron(a(1:3:end,:),ones(3,1));

让我们测试一下:

a=[1 3 5
   2 3 6
   1 1 1
   3 5 4
   5 5 5
   8 8 0]

a-kron(a(1:3:end,:),ones(3,1))

ans =
 0     0     0
 1     0     1
 0    -2    -4
 0     0     0
 2     0     1
 5     3    -4

编辑

这是一个bsxfun解决方案(不太优雅,但希望更快):

Edit

Here's a bsxfun solution (less elegant, but hopefully faster):

a-reshape(bsxfun(@times,ones(1,3),permute(a(1:3:end,:),[2 3 1])),3,[])'

ans =

 0     0     0
 1     0     1
 0    -2    -4
 0     0     0
 2     0     1
 5     3    -4

编辑2

好吧,这让我产生了好奇,因为我知道bsxfun对于更大的阵列大小开始变得效率较低.因此,我尝试使用timeit来检查我的两个解决方案(因为它们是一种衬板,所以很容易).这里是:

Edit 2

Ok, this got me curios, as I know bsxfun starts to be less efficient for bigger array sizes. So I tried to check using timeit my two solutions (because they are one liners it's easy). And here it is:

range=3*round(logspace(1,6,200));
for n=1:numel(range)
    a=rand(range(n),3);
    f=@()a-kron(a(1:3:end,:),ones(3,1));
    g=@() a-reshape(bsxfun(@times,ones(1,3),permute(a(1:3:end,:),[2 3 1])),3,[])';
    t1(n)=timeit(f);
    t2(n)=timeit(g);
end
semilogx(range,t1./t2);

所以我没有测试for循环和Divkar的bsxfun,但是您可以看到,对于小于3e4的数组,kron比bsxfun更好,而且这种变化在较大的数组上发生(比率< 1意味着kron花费的时间更少给定数组的大小).这是在Matlab 2012a win7(i5机)上完成的

So I didn't test for the for loop and Divkar's bsxfun, but you can see that for arrays smaller than 3e4 kron is better than bsxfun, and this changes at larger arrays (ratio of <1 means kron took less time given the size of the array). This was done at Matlab 2012a win7 (i5 machine)

这篇关于MATLAB:按特定行减去矩阵子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆