MATLAB Answers

Getting rid of loops

37 views (last 30 days)
Wesso
Wesso on 9 Jan 2021
Commented: Wesso on 10 Jan 2021
Hi, I am trying to clean matrix A (which is a 1064 x 4 matrix) while relying in the cleaning process on Matrices B and C that have the same size as A (Mat file attached). I developed a loop to clean A but I feel that a loop is unnecessary and that I can do it without relying on loops. Could the cleaning process be done much more efficiently? Your help is appreciated.
for i=1:size(A,1)
for j=1:size(A,2)
if A(i,j)<1 && A(i,j)>0 % this is the first issue in the cleaning process. A values between 0 and 1 should be equal to the respective value in matrix X
A (i,j)=B(i,j);
end
if A(i,j)<C(i,j) % this is the 2nd issue I am facing A values lower than their respective C values are erroneous and should be replaced by NaN
A (i,j)=nan;
end
if B(i,j)>100 %this is the third issue: When B is greater than 100, A values should be equal to B values
A (i,j)=B(i,j);
elseif B(i,j)<0 %This is the fourth issue: negative percentages are missing observations
A(i,j)=-999;
end
if C(i,j)==0%This is the 5th issue: when C is zero, A should be zero as well
A(i,j)=0;
end
end
end

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 9 Jan 2021
Edited: Stephen Cobeldick on 9 Jan 2021
Logical indexing is much simpler than using loops:
idx = A<1 & A>0;
A(idx) = B(idx);
A(A<C) = NaN;
idy = B>100 | B<0;
A(idy) = B(idy);
A(C==0) = 0
  4 Comments
Wesso
Wesso on 10 Jan 2021
my bad I was looking at the wrong matrix. Thanks a lot

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 9 Jan 2021
Edited: Image Analyst on 9 Jan 2021
Did you consider just using a mask and no for loops?
mask = A<1 & A>0; % this is the first issue in the cleaning process. A values between 0 and 1 should be equal to the respective value in matrix X
A(mask) = B(mask);
mask = A<C; % this is the 2nd issue I am facing A values lower than their respective C values are erroneous and should be replaced by NaN
A(mask) = nan;
mask = B>100; %this is the third issue: When B is greater than 100, A values should be equal to B values
A(mask) = B(mask);
mask = B<0; %This is the fourth issue: negative percentages are missing observations
A(mask) = -999;
mask = C==0%This is the 5th issue: when C is zero, A should be zero as well
A(mask) = 0;
  7 Comments
Wesso
Wesso on 10 Jan 2021
my bad I was looking at the wrong matrix. Thanks a lot

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by