热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何让数组在matlab中启动并开始-Howtogetanarraytostartandbeginwhereyouwantinmatlab

Ihaveanarraythatstartswithafewdozen0s,proceedswithafewnumbers,andthanendswitha

I have an array that starts with a few dozen 0's, proceeds with a few numbers, and than ends with a few more zeros. I want to make a new array with just the numbers, not the zeros. it looks something like this

我有一个数组,从几十个0开始,继续几个数字,然后结束几个零。我想用数字而不是零来创建一个新数组。它看起来像这样

0 0 0 0 0 0 0 0 0 0 245 35635 3563 6346 3465 34 235 46 356 36 0 0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0 245 35635 3563 6346 3465 34 235 46 356 36 0 0 0 0 0 0 0 0 0 0 0

I want to make an array that start like this in matlab

我想在matlab中创建一个像这样开始的数组

245 35635 3563 6346 3465 34 235 46 356 36

245 35635 3563 6346 3465 34 235 46 356 36

Any ideas. I tried to use if statements within a loop, but I can only get the zeros at the end to go away

有任何想法吗。我试图在循环中使用if语句,但我只能在最后得到零消失

5 个解决方案

#1


4  

This should also work:

这应该也有效:

newArray = oldArray(oldArray>0);

#2


2  

the find command in matlab solves this. try:

matlab中的find命令解决了这个问题。尝试:

if a = [0 0 0 2 3 4 2 0 0 0]; then

如果a = [0 0 0 2 3 4 2 0 0 0];然后

a(find(a==0))=[];

or

要么

a(a==0)=[];

removes the zeros without for loop

删除没有for循环的零

#3


1  

"Logical indexing" is the most efficient way to do something like this.

“逻辑索引”是执行此类操作的最有效方法。

dataWithoutZeros = data(data ~= 0);

This is because in addition to the usual way of indexing matrices in MATLAB, by specifying a set of index positions, you can also specify an array of logical values of the same dimension as the array

这是因为除了在MATLAB中索引矩阵的常用方法之外,通过指定一组索引位置,您还可以指定与数组具有相同维度的逻辑值数组

data = [10 20 30 40];
a = data([1 3]); % a has value [10 30]
b = data(logical([1 0 1 0])); % b has the same value as a

#4


1  

Assuming you only want to cut off the leading and trailing zeroes, you will need a solution that does not get rid of the middle zeroes. In this case I would suggest the following:

假设您只想切断前导零和尾随零,那么您将需要一个不会消除中间零的解决方案。在这种情况下,我会建议如下:

x = [ 0 0 1 2 0 -3 0]
x(find(x,1,'first'):find(x,1,'last'))

Will give:

会给:

1     2     0    -3

If you are worried about precision, try this:

如果你担心精度,试试这个:

x = [ 0 0 1 2 0 -3 0]
idx = abs(x)>1e-12
x(find(idx,1,'first'):find(idx,1,'last'))

#5


0  

Or even, for less effort at the fingertips and arguably less comprehensible, take advantage of a language which thinks that 0 is the same as not true ...

或者甚至,为了减少指尖上的努力并且可以说理解力较低,可以利用一种认为0与真实相同的语言......

myvector(find(myvector))

returns just the non 0 elements of myvector.

只返回myvector的非0元素。


推荐阅读
author-avatar
minggute_111
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有