element by element subtraction using bsxfun

조회 수: 1 (최근 30일)
John Draper
John Draper 2016년 6월 25일
댓글: John Draper 2016년 6월 27일
Hi everyone,
I have an array, for simplicity let it be:
a = [1 2 3; 4 5 6; 7 8 10];
I would like to perform an element by element subtraction, I have using:
Av = bsxfun(@minus, a(:)', a(:));
However this does not give me the desired result. For the resulting array I want:
Aresult = [0 -1 -2 1 0 -1 2 1 0; -3 -4 -5 -2 -3 -4 -1 -2 -3;-6 -7 -8 -5 -6 -7 -4 -5 -6 ....(continued)]
So to explain the desired result I would like to take an individual element and then subtract the surrounding elements to create a 3x3 sub array in the larger 9x9 array. So in the array above going from left to right
1-0 = 0;
1-2 = -1;
1-3 = -2; (going to the next row down)
1-4 = -3;
1-5 = -4;
1-6 = -5; (going down a row again)
1-7 = -6;
1-8 = -7;
1-9 = -8;
So these results would provide the first 3x3 sub array. This would then be repeated for all elements of the initial array a.
I would be very grateful for any help/ comments you can provide, I hope my explanation wasn't too confusing :).
Thanks, John.

채택된 답변

Stephen23
Stephen23 2016년 6월 25일
편집: Stephen23 2016년 6월 25일
This works for an array whatever its size:
>> A = [1 2 3; 4 5 6; 7 8 9]
A =
1 2 3
4 5 6
7 8 9
>> cell2mat(arrayfun(@(a)a-A,A,'UniformOutput',false))
ans =
0 -1 -2 1 0 -1 2 1 0
-3 -4 -5 -2 -3 -4 -1 -2 -3
-6 -7 -8 -5 -6 -7 -4 -5 -6
3 2 1 4 3 2 5 4 3
0 -1 -2 1 0 -1 2 1 0
-3 -4 -5 -2 -3 -4 -1 -2 -3
6 5 4 7 6 5 8 7 6
3 2 1 4 3 2 5 4 3
0 -1 -2 1 0 -1 2 1 0

추가 답변 (2개)

Andrei Bobrov
Andrei Bobrov 2016년 6월 25일
편집: Andrei Bobrov 2016년 6월 25일
t = ones(size(a));
out = kron(a,t) - kron(t,a);
or
[m,n] = size(a);
out = repelem(a,m,n) - repmat(a,m,n);
  댓글 수: 1
John Draper
John Draper 2016년 6월 27일
Thank you, this works and produces the desired result!

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


John Draper
John Draper 2016년 6월 25일
Hi everyone just an update. I have written some code that will return the required result:
if true
a = [1 2 3; 4 5 6; 7 8 9];
Av1 = a(1,1) - a(1:3,1:3);
Av2 = a(1,2) - a(1:3,1:3);
Av3 = a(1,3) - a(1:3,1:3);
Av4 = a(2,1) - a(1:3,1:3);
Av5 = a(2,2) - a(1:3,1:3);
Av6 = a(2,3) - a(1:3,1:3);
Av7 = a(3,1) - a(1:3,1:3);
Av8 = a(3,2) - a(1:3,1:3);
Av9 = a(3,3) - a(1:3,1:3);
Av = [Av1 Av2 Av3; Av4 Av5 Av6; Av7 Av8 Av9];
% code
end
However I feel there must be a more elegant want to write this, perhaps for an array that doesn't necessarily have a size of 3 x 3. Thanks again, John.

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by