How can I subtract a 2-d array from every slice of a 3-d array?

15 views (last 30 days)
A is a 512 x 512 x 200 array representing a stack of 200 monochrome images of resolution 512x512.
d = size(A)
d =
512 512 200
C is an 'offset' image that I want to deduct from each image in A. C has dimensions 512 x 512.
A(:,:,1) = A(:,:,1) - C;
A(:,:,2) = A(:,:,2) - C;
A(:,:,3) = A(:,:,3) - C;
A(:,:,4) = A(:,:,4) - C;
% and so on
I know that I could do a 'for' loop to handle this. Is there a better 'one-line' solution?

Accepted Answer

Walter Roberson
Walter Roberson on 18 Jul 2022
A = randi(9, 5, 5, 3);
C = randi(9, 5, 5);
newA = A - C;
%demonstrate that it worked
A(:,:,1)
ans = 5×5
3 2 2 9 1 6 8 6 1 5 5 1 5 6 2 6 6 2 5 7 7 4 8 5 7
C
C = 5×5
5 6 5 8 1 2 7 9 3 7 9 7 5 7 2 1 6 8 9 6 8 4 2 5 8
A(:,:,1) - C
ans = 5×5
-2 -4 -3 1 0 4 1 -3 -2 -2 -4 -6 0 -1 0 5 0 -6 -4 1 -1 0 6 0 -1
newA(:,:,1)
ans = 5×5
-2 -4 -3 1 0 4 1 -3 -2 -2 -4 -6 0 -1 0 5 0 -6 -4 1 -1 0 6 0 -1

More Answers (0)

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!