How to subtract elements in a matrix

20 ビュー (過去 30 日間)
Jakub Nosek
Jakub Nosek 2017 年 10 月 21 日
コメント済み: Jakub Nosek 2017 年 10 月 21 日
Hello,
I have a matrix and I need to subtract every element from each other in each row. So, for example, if I have a matrix A=[1 2 3; 4 8 9] the result should be for example this B=[1 2 1; 4 5 1] - the sequence is not important. But I need to know that the result in the matrix B corresponds to a particular elements' subtraction in matrix A. So if I have for example a subtraction of 2-1, which is A(1,2)-A(1,1) in matrix A and the result is 1 in matrix B I need to know that 1 corresponds to A(1,2)-A(1,1) and keep track of it.
I have tried to do it with cycles and also with a "bsxfun" function but unfortunately can't get the correct result.
g=[1 3 8; 4 6 2];
[u,v]=size(g);
for i=1:u
for j=1:v
a(i,j)=bsxfun(@minus,g(i,j),g(i,j)');
end
end
I'll be glad if anyone can help me. Thanks
  4 件のコメント
KL
KL 2017 年 10 月 21 日
編集済み: KL 2017 年 10 月 21 日
It's still not consistent with your expected result in B! Your A is
A = [1 2 3; 4 8 9];
and your expected B is
B = [1 2 1; 4 5 1];
if you want to subtract every element from each other (even if you store the absolute value), your B should rather be,
B = [4 2 0; 13 5 3]
Do you understand?
Jakub Nosek
Jakub Nosek 2017 年 10 月 21 日
Well, there must be a misunderstanding. Sorry about that. Let's say we have A=[1 2 3; 4 8 9] Now I want to do this: 1-2, 1-3, 2-3 and 4-8,4-9,9-8
In a real matrix that I want to use, the elements are aircraft's altitudes and thus the columns are individual aircraft and rows times in which the altitudes were measured. I need to continuously check the altitude separation between all aircraft. Hence I need to calculate the altitude differences in every time step.

サインインしてコメントする。

採用された回答

Roger Stafford
Roger Stafford 2017 年 10 月 21 日
You don't need a for-loop.
C = nchoosek(1:size(A,2),2);
B = A(:,C(:,2))-A(:,C(:,1));
  1 件のコメント
Jakub Nosek
Jakub Nosek 2017 年 10 月 21 日
Thanks a lot! This works!

サインインしてコメントする。

その他の回答 (1 件)

KL
KL 2017 年 10 月 21 日
編集済み: KL 2017 年 10 月 21 日
Ok, I guess you want to subtract following column with the current column,
B = circshift(A,-1,2)-A
But your expected B rather looks like the result of,
B = [A(:,2)-A(:,1) A(:,3)-A(:,1) A(:,3)-A(:,2)]

Community Treasure Hunt

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

Start Hunting!

Translated by