[英]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.
我正在循环,如果距离小于商店,5,则将其输入数组 closeHome。 While the array accepts the true values, I also get zeros in the closeHome array.
虽然数组接受真实值,但我也在 closeHome 数组中得到零。 How do I collect the data into the array without these zeros with the desired output, closeHome = 5.0000 4.1231 2.8284?
如何将没有这些零的数据收集到具有所需输出的数组中,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
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
.好吧,您的问题是,您将值放在
closeHome
第j
个位置,这导致closeHome
始终具有size(distance)
元素,并且所有不满足条件的元素都将为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.无论如何,您还可以使用 matlabs 的逻辑索引能力来简化此代码。 You can just replace your for loop by this simple line:
你可以用这个简单的行替换你的 for 循环:
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.在这种情况下,
distance<=store
将创建一个逻辑数组,其中所有小于store
的距离位置为 1,所有其他位置为 0。 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.只是让您知道:在 matlab 编程中,将
i
和j
用作变量被认为是一种不好的做法,因为它们代表虚数单位。 So you might consider changing these and use (eg) ii
and jj
or smth completely different.因此,您可能会考虑更改这些并使用(例如)
ii
和jj
或完全不同的 smth。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.