Find the difference between all columns of a given row of a matrix

조회 수: 7 (최근 30일)
I have MXL matrix. For each row, I want to find the absolute difference between the columns, without repeating. For example, if I have a row
a = [a11 a12 a13 a14]
I want to find
[abs(a11-a12) abs(a11-a13) abs(a11-a14) abs(a12-a13) abs(a12-a14) abs(a13-a14)]
How can I do that withoug for loops?
EDIT: I found this method
pdist([2 3 1 4]',@(x,y) x-y)
which looks like what I'm looking for, but I need to extend this for a matrix, and perform the above for all rows.

채택된 답변

Antoni Garcia-Herreros
Antoni Garcia-Herreros 2023년 5월 8일
Hello MAWE,
You could use the function nchoosek:
Something like this might work for your case:
A=rand(4,5); % Generate data for the example
perms = nchoosek(1:size(A,2),2); % Find all the possible permutations
D=abs(A(:,perms(:,2))-A(:,perms(:,1))) % Compute the difference
D = 4×10
0.1875 0.5928 0.3519 0.1090 0.4053 0.1644 0.0785 0.2409 0.4838 0.2429 0.3220 0.2441 0.1334 0.3684 0.0779 0.4555 0.6904 0.3775 0.6125 0.2350 0.4037 0.4237 0.0883 0.1470 0.8274 0.3155 0.2568 0.5120 0.5707 0.0587 0.5416 0.0068 0.6400 0.3387 0.5348 0.0984 0.2029 0.6332 0.3319 0.3013
Hope this helps

추가 답변 (1개)

Luca Ferro
Luca Ferro 2023년 5월 8일
편집: Luca Ferro 2023년 5월 8일
a=[1 3 5 -3];
aPerms=nchoosek(a,2); %generates all unique couples
absDiff=abs(aPerms(:,1)-aPerms(:,2))' %absolute difference of said couples, ' to transpose
absDiff = 1×6
2 4 4 2 6 8
  댓글 수: 1
MAWE
MAWE 2023년 5월 8일
Thanks, this seems to work on a vector. How can I extend to a matrix?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by