Find positive elements in a 3D matrix

2 次查看(过去 30 天)
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

回答(3 个)

KL
KL 2017-11-30
编辑:KL 2017-11-30
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 个评论
Jan
Jan 2017-11-30
Note: -dummy is cheaper than -1 * dummy.

请先登录,再进行评论。


Jan
Jan 2017-11-30
编辑:Jan 2017-11-30
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 2017-11-30
Tank you Jan! You solve my problem

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by