Find positive elements in a 3D matrix

Hi, I am dealing with a 3D matrix of 10000 rows (MR_ene), 5 columns and 19 rows of depth. I would like to save in another matrix (always 10000x5x19, MR_ene_pos)only the depth rows with all positive elements.... I tried this code
MR_ene_pos=zeros(10000,5,19);
for i=1:10000
for k=1:19
for j=1:5
if MR_ene(i,j,k)>0
MR_ene_pos(i,j,k)=MR_ene(i,j,k);
else
MR_ene_pos(i,:,k)=0;
end
end
end
end
It works but in the 5th element of the colums j is positive,it is considered in the resulting matrix (even if one of the previous elements (j=1...,4) was negative, while the code purpous is to set zero each of the 19 rows where just 1 element is negative _ after analyzing the first "layer" (i=1,j=1:5,z=1:19) this procedure is repeated on the 10000 rows Maybe it will work using a break statement..... Tank you in advice

Antworten (3)

KL
KL am 30 Nov. 2017
Bearbeitet: KL am 30 Nov. 2017

0 Stimmen

EDITED
If you want to copy the elements only if all the elements in a row in that page is positive. In that case, you can use all command with just one loop along the third dimension (page). I'll show you with a small example,
first create some dummy data with all negative elements,
dummy = -rand(3,5,7);
now I'll make certain rows positive,
dummy(1,:,2) = -1*dummy(1,:,2);
dummy(3,:,3) = -1*dummy(3,:,3);
dummy(1,:,5) = -1*dummy(1,:,5);
now I want to copy only these rows in the new matrix and remaining should be zeros. So,
for p=1:size(dummy,3)
indx = all(dummy(:,:,p)>0,2);
dummy_pos(indx,:,p) = dummy(indx,:,p);
end
Hope this is what you need.

3 Kommentare

Alessandro Cerrano
Alessandro Cerrano am 30 Nov. 2017
tank you KL, however this is not the objective, maybe I was not enough clear,
Actually in each of the 19 pages there are both positive and negative elements. I want do copy each row (of the 10000) which has all the 5 column elements positive, repeating this procedure for all the 19 pages.
KL
KL am 30 Nov. 2017
Ah ok, see my edited answer.
Jan
Jan am 30 Nov. 2017
Note: -dummy is cheaper than -1 * dummy.

Melden Sie sich an, um zu kommentieren.

Jan
Jan am 30 Nov. 2017
Bearbeitet: Jan am 30 Nov. 2017

0 Stimmen

match = repmat(all(MR_ene > 0, 2), 1, 5, 1);
MR_ene_pos = zeros(10000,5,19);
MR_ene_pos(match) = ME_ene(match);
UNTESTED.
Your loop would be:
MR_ene_pos = zeros(10000,5,19);
for i=1:10000
for k=1:19
if all(MR_ene(i,:,k) > 0)
MR_ene_pos(i,:,k) = MR_ene(i,:,k);
end
end
end
Alessandro Cerrano
Alessandro Cerrano am 30 Nov. 2017

0 Stimmen

Tank you Jan! You solve my problem

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by