subtraction of each row with every other row

2 次查看(过去 30 天)
I want to subtract each row of the matrix with every other row and store it in a different bigger size matrix, for example-
A=[1,2,3:4,5,6:7,8,9];
B[1-4,2-5,3-6; 1-7,2-8,3-9; 4-1,5-2,6-3; 4-7,5-8,6-9; 7-1,8-2,9-3; 7-4,8-5,9-6];
That means if the original matrix is of size 3×3 then the answer matrix would be 6×3.
My original matrix is of size 40×150.
  3 个评论
ST
ST 2020-12-8
That was a typo, apology. Thanks for your efforts though.
Paul Hoffrichter
Paul Hoffrichter 2020-12-8
Could you fix up your OP removing any typos, and show the desired results.

请先登录,再进行评论。

回答(2 个)

Paul Hoffrichter
Paul Hoffrichter 2020-12-9
B = repmat(A, N,1) - repelem(A,N,1);

Paul Hoffrichter
Paul Hoffrichter 2020-12-8
编辑:Paul Hoffrichter 2020-12-8
A=[1,2,3,4,5; 6,7,8,9,10; 11, 12, 13, 14, 15;16, 17, 18, 19, 20];
c = nchoosek(1:size(A, 1),2);
c2 = [c; fliplr(c)];
B = zeros( length(c2), size(A,2));
for ii = 1: size(c2,1)
[r1 r2] = deal( c2(ii,1), c2(ii,2) );
B(ii,:) = A(r1,:) - A(r2,:);
end
B
B =
-5 -5 -5 -5 -5
-10 -10 -10 -10 -10
-15 -15 -15 -15 -15
-5 -5 -5 -5 -5
-10 -10 -10 -10 -10
-5 -5 -5 -5 -5
5 5 5 5 5
10 10 10 10 10
15 15 15 15 15
5 5 5 5 5
10 10 10 10 10
5 5 5 5 5
  3 个评论
Paul Hoffrichter
Paul Hoffrichter 2020-12-8
编辑:Paul Hoffrichter 2020-12-8
I kept the numbers more manageable to compare results.
METHOD_ONE = 0
N=20;
step=50;
N=3;
step=4;
rng(10);
A=randi(5*N, N, step);
if METHOD_ONE
c = nchoosek(1:size(A, 1),2);
c2 = [c; fliplr(c)];
B = zeros( length(c2), size(A,2));
for ii = 1: size(c2,1)
[r1 r2] = deal( c2(ii,1), c2(ii,2) );
B(ii,:) = A(r1,:) - A(r2,:);
end
else
B=zeros(N*N,step);
count=1;
jj=1:(N*N);
n=N;
for ii=1:N
rowNums = jj(count:count+n-1);
B( rowNums ,:) = A - A(ii, :);
count=count+N;
end
end
A
B
Output:
METHOD_ONE =
0
A =
12 12 3 2
1 8 12 11
10 4 3 15
B =
0 0 0 0
-11 -4 9 9
-2 -8 0 13
11 4 -9 -9
0 0 0 0
9 -4 -9 4
2 8 0 -13
-9 4 9 -4
0 0 0 0
METHOD_ONE =
1
A =
12 12 3 2
1 8 12 11
10 4 3 15
B =
11 4 -9 -9
2 8 0 -13
-9 4 9 -4
-11 -4 9 9
-2 -8 0 13
9 -4 -9 4
As you can see, your code has rows of 0's when you subtract a row from itself. The ordering of rows of B are different between the two versions.
Also, half of the rows are just the negation of the other half. Do you need both halves?
ST
ST 2020-12-9
Yes, I need zero rows too. Thanks for your answer.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by