subtraction of each row with every other row

조회 수: 2 (최근 30일)
ST
ST 2020년 12월 8일
답변: Paul Hoffrichter 2020년 12월 9일
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