开发者

How can I concatenate ranges of numbers into an array in MATLAB?

开发者 https://www.devze.com 2023-01-16 16:37 出处:网络
For example, I want to combine two ranges of numbers like this: 1 2 3 4 5 11 12 13 14 15 16 17 18 19 开发者_JAVA技巧20

For example, I want to combine two ranges of numbers like this:

1 2 3 4 5 11 12 13 14 15 16 17 18 19 开发者_JAVA技巧20

So, I tried:

a = 1:5,11:20

but that didn't work.

I also want to do this in a non-hardcoded way so that the missing 5 elements can start at any index.


For your example, you need to use square brackets to concatenate your two row vectors:

a = [1:5 11:20];

Or to make it less hardcoded:

startIndex = 6;  %# The starting index of the 5 elements to remove
a = [1:startIndex-1 startIndex+5:20];

You may also want to check out these related functions: HORZCAT, VERTCAT, CAT.

There are a few other ways you could do this as well. For one, you could first make the entire vector, then index the elements you don't want and remove them (i.e. set them to the empty vector []):

a = 1:20;      %# The entire vector
a(6:10) = [];  %# Remove the elements in indices 6 through 10

You could also use set operations to do this, such as the function SETDIFF:

a = setdiff(1:20,6:10);  %# Get the values from 1 to 20 not including 6 to 10
0

精彩评论

暂无评论...
验证码 换一张
取 消