首页 > 解决方案 > MATLAB:删除从循环收集的数组中的零点

问题描述

如何从循环中收集的数组中删除零?我正在循环,如果距离小于商店 5,则将其输入数组 closeHome。虽然该数组接受真实值,但我在 closeHome 数组中也得到了零。如何在没有这些零的情况下将数据收集到具有所需输出的数组中,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

标签: arraysmatlabloops

解决方案


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.


推荐阅读