arrays - 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
解决方案
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.
推荐阅读
- python - 绘制从整个数据生成的图像的某些部分
- php - 带有 Pusher 的 Laravel Echo 未在私人频道上接收消息
- c# - 将静态扩展分辨率限制为最窄的匹配签名
- keras - ValueError: name_scope 的名称在尝试在 TF2.0 中构建模型类时必须是字符串
- angular - 如何从组件中的服务方法获取 catchError 消息?
- tensorflow - tensorflow 在 anaconda 提示符下工作,但不在命令提示符下
- oracle - Maximo 的出站集成:物化视图不是合适的选择是否有原因?
- c# - 从字典返回差异
- android - 如何修复按钮中的错误意图和音效?
- django - 502 Bad Gateway nginx/1.14.0 (Ubuntu) digitalocean vps django、nginx 和 gunicorn