MATLAB Answers


How can I rewrite this code as to ommit the for loop?

Asked by charles on 28 Jul 2017
Latest activity Commented on by Star Strider
on 28 Jul 2017
I'm writting a script for root (of plants) analysis. I work with quite large datasets (1000*1000*1000 pixels) and therefor I would like to optimalize the processing speed of the script. Right now I am using a for loop in order to assign a value of 1 to certain points in the volume with the rest being 0. My script looks as follows
V2 = zeros(dimx,dimy,dimz);
for x = 1:dimx
for y = 1:dimy
for z = 1:dimz
if labda3(x,y,z) > 0 ;
V2(x,y,z) = 0;
elseif labda2(x,y,z) > 0 ;
V2(x,y,z) = 0;
else V2(x,y,z) = 1;
Since Matlab is not very fast when using for loops I assumed that there is a faster way of doing this, however I cannot think of any myself. Can anyone help me with this?


Sign in to comment.

1 Answer

Answer by Star Strider
on 28 Jul 2017
 Accepted Answer

See if this does what you want:
labda2 = randn(5, 5, 2) % Create Data
labda3 = randn(5, 5, 2) % Create Data
V2 = ones(size(labda2));
V2((labda2>0) | (labda3>0)) = 0
If it does what you want with the test data, it should work with your larger matrix.


Thx! This does exactly what I want!
As always, my pleasure!

Sign in to comment.