Remove elements from array based on logical condition

52 views (last 30 days)
I am trying to write a for loop/if statement that goes through two arrays and compares the elements of each array to each other. If both values at the specified index equal 0, then I want to remove those two elements.
When I try and run my code, it seems to freeze. Any suggestions on how I can go about fixing this?
% x = array with size 1x875175
% y = array with size 1x875175
% Goal: when element at x AND y = 0, then delete. I do not want an ordered pair of (0,0).
for k = 1:length(x)
if x(1,k) == 0 & y(1,k) == 0
x(:,k) = [];
y(:,k) = [];
end
end
If I try to script the if statement with x(1,k) and y(1,k) then I get an error: A null assignment can have only one non-colon index.
Alternative Option: Instead of finding where the indexed elements are equal to 0, what about finding where both elements are > 0 and saving those elements?
Thanks!

Accepted Answer

Walter Roberson
Walter Roberson on 26 Mar 2019
for k = size(x,2): -1 : 1
Remember that when you delete a column from a matrix, that all later columns "fall down" to occup the missing space. If you delete column 7 (for example) that what used to be column 8 becomes 7, what was 9 becomes 8, and so on, so that the matrix would become one column shorter. If you delete (say) 10 columns, then when your for loop reached column 875175-10+1 then the index which would easily have fit into the original length will no longer fit into the array that has had columns deleted from it.
Furthermore, if you examine (say) column 7 and delete it, and you are incrementing k each time, then column 8 "falls down" into column 7, and your for increments to 8, but what was in column 8 now is what used to be in column 9... and you have managed to skip looking at what used to be in column 8.
Both of these problems disappear when you use the technique I show above about looping backwards from the end.
... but a much better solution would be to vectorize.
mask = x == 0 & y == 0;
x(mask) = [];
y(mask) = [];

More Answers (0)

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!