Minimalist
Minimalist

Reputation: 975

MATLAB: Removing Zeros in Array collected from Loop

How do I remove the zeros from an array that has been collected from a loop? I am looping and if distance is less than the store, 5, then enter it into the array, closeHome. While the array accepts the true values, I also get zeros in the closeHome array. How do I collect the data into the array without these zeros with the desired output, closeHome = 5.0000 4.1231 2.8284?

x = [5 7 4 1 2]'
y = [1 2 3 4 2]'
distance = sqrt(x.^2 + y.^2)
store = 5;

for j=1:size(distance)
 if distance(j) <= store
      closeHome(j) = distance(j)
 end       
end

Upvotes: 0

Views: 59

Answers (1)

Max
Max

Reputation: 1481

Well your problem is, that you are putting your values on the j-th position of closeHome which results in closeHome always having size(distance) elements and all the elements for which the condition is not met will be 0. You can avoid this by changing the code like this:

x = [5 7 4 1 2].';
y = [1 2 3 4 2].';
distance = sqrt(x.^2 + y.^2);
store = 5;
closeHome=[];
for j=1:size(distance)
  if distance(j) <= store
    closeHome(end+1)=distance(j);
  end
end

Anyway you can also simplify this code a lot using matlabs ability of logical indexing. You can just replace your for loop by this simple line:

closeHome=distance(distance<=store);

In this case distance<=store will create a logical array having 1s for all positions of distance that are smaller than store and 0s for all other position. Then indexing distance with this logical array will give you the desired result.
And just for you to know: In matlab programming it's considered a bad practice to use i and j as variables, because they're representing the imaginary unit. So you might consider changing these and use (e.g) ii and jj or smth completely different.

Upvotes: 3

Related Questions