Array Indexing using logicals in higher dimensions

I have a 3D array: A = 10x10x100 where the 2D data (10x10) is stacked in the 3rd dimension.
I am using a logical mask: B which is 10x10 and has 1s at the locations where I want to access the data in every 2D slice of the 3D array.
I would like to use the logical mask to access the data from each 2D slice and perform some simple operations - such as compute mean - for all slices (in the 3rd dimension). I am currently using a for loop as below.
for i = 1:size(A,3)
temp = A(:,:,i);
mean_out(i) = mean(temp(B));
end
Is it possible to achieve this without a for loop?
Thanks.

 Akzeptierte Antwort

Ameer Hamza
Ameer Hamza am 20 Mai 2020
Bearbeitet: Ameer Hamza am 20 Mai 2020
Try this
mean_val = squeeze(mean(A.*B, [1 2]))
Similarly
squeeze(max(A.*B, [], [1 2])) % maximum value
squeeze(min(A.*B, [], [1 2])) % minimum value

4 Kommentare

AP
AP am 20 Mai 2020
Thanks Ameer, but I want to exclude the 0s from the mean.
squeeze(mean(nonzeros(A.*repmat(B,[1,1,size(A)])), [1 2])) does not work either because nonzeros reduces the array to a column.
Try this. It replaces 0s with nan and then uses nanmean()
A = rand(10,10,100);
B = rand(10,10)>0.5;
M = A.*B;
M(M==0) = nan;
mean_val = squeeze(nanmean(M, [1 2]))
Also, it does not reduce the matrix to the column. It calculates the mean of each 3D slice separately. I used squeeze() to convert the final answer to a column matrix. You can run it without squeeze, and you will get a 3D matrix
mean_val = nanmean(M, [1 2])
AP
AP am 20 Mai 2020
Bearbeitet: AP am 20 Mai 2020
Thanks, this works for me. I made the mask itself NaNs to make it more general.
B = double(B); B(B==0) = nan;
mean_val = squeeze(nanmean(A.*B, [1 2]))
In that case try
A = rand(10,10,100);
B = rand(10,10)>0.5;
mask = repmat(B, 1, 1, size(A,3));
M = A;
M(mask) = nan;
mean_val = nanmean(M, [1 2])

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2019a

Gefragt:

AP
am 19 Mai 2020

Kommentiert:

am 20 Mai 2020

Community Treasure Hunt

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

Start Hunting!

Translated by