简体   繁体   English

Matlab从数组中删除不需要的数字

[英]Matlab removing unwanted numbers from array

I have got a matlab script from net which generates even numbers from an inital value. 我有一个来自net的matlab脚本,它从初始值生成偶数。 this is the code. 这是代码。

n = [1 2 3 4 5 6];
iseven = [];
for i = 1: length(n);
if rem(n(i),2) == 0
iseven(i) = i;
else iseven(i) = 0;
end
end
iseven

and its results is this 它的结果是这样的

iseven =

     0     2     0     4     0     6

in the result i am getting both even numbers and zeros, is there any way i can remove the zeros and get a result like this 在结果我得到偶数和零,是否有任何方法我可以删除零并获得这样的结果

iseven =

         2    4     6

You can obtain such vector without the loop you have: 您可以在没有循环的情况下获得此类向量:

n(rem(n, 2)==0)
ans =

 2     4     6

However, if you already have a vector with zeros and non-zeroz, uou can easily remove the zero entries using find : 但是,如果您已经有一个带零和非零的向量,则可以使用find轻松删除零条目:

iseven = iseven(find(iseven));

find is probably one of the most frequently used matlab functions. find可能是最常用的matlab函数之一。 It returns the indices of non-zero entries in vectors and matrices: 它返回向量和矩阵中非零项的索引:

% indices of non-zeros in the vector
idx = find(iseven);

You can use it for obtaining row/column indices for matrices if you use two output arguments: 如果使用两个输出参数,则可以使用它来获取矩阵的行/列索引:

% row/column indices of non-zero matrix entries
[i,j] = find(eye(10));

To display only non-zero results, you can use nonzeros 要仅显示非零结果,可以使用nonzeros

iseven = [0     2     0     4     0     6]

nonzeros(iseven)

ans =

     2     4     6

The code you downloaded seems to be a long-winded way of computing the range 您下载的代码似乎是计算范围的冗长方式

2:2:length(n)

If you want to return only the even values in a vector called iseven try this expression: 如果您只想在名为iseven的向量中返回偶数值, iseven尝试以下表达式:

iseven(rem(iseven,2)==0)

Finally, if you really want to remove 0 s from an array, try this: 最后,如果你真的想从数组中删除0 ,请尝试这样做:

iseven = iseven(iseven~=0)

Add to the end of the vector whenever you find what you're looking for. 只要找到您要查找的内容,就可以添加到矢量的末尾。

n = [1 2 3 4 5 6]; 
iseven = []; % has length 0
for i = 1: length(n);
  if rem(n(i),2) == 0
    iseven = [iseven i]; % append to the vector 
  end
end
iseven

要从程序中删除所有零,我们可以使用以下命令,命令是 -

iseven(iseven==0)=[]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM