Clear Filters
Clear Filters

Find positive elements in a 3D matrix

2 views (last 30 days)
Alessandro Cerrano
Alessandro Cerrano on 30 Nov 2017
Answered: Alessandro Cerrano on 30 Nov 2017
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

Answers (3)

KL
KL on 30 Nov 2017
Edited: KL on 30 Nov 2017
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 Comments
KL
KL on 30 Nov 2017
Ah ok, see my edited answer.
Jan
Jan on 30 Nov 2017
Note: -dummy is cheaper than -1 * dummy.

Sign in to comment.


Jan
Jan on 30 Nov 2017
Edited: Jan on 30 Nov 2017
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 on 30 Nov 2017
Tank you Jan! You solve my problem

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!