poster
2019-12-10, 20:48
例如,我要合并两个数字范围,如下所示:
1 2 3 4 5 11 12 13 14 15 16 17 18 19 20 因此,我尝试:
a = 1:5,11:20 但这没用。
我还想以一种非硬编码的方式执行此操作,以便缺少的5个元素可以从任何索引处开始。
回答:
对于您的示例,您需要使用方括号 (http://www.mathworks.com/help/techdoc/ref/specialcharacters.html)来连接两个行向量:
a = [1:5 11:20]; 或减少其硬编码:
startIndex = 6; %# The starting index of the 5 elements to remove a = [1:startIndex-1 startIndex+5:20]; 您可能还需要检查以下相关功能: HORZCAT (http://www.mathworks.com/help/techdoc/ref/horzcat.html) , VERTCAT (http://www.mathworks.com/help/techdoc/ref/vertcat.html) , CAT (http://www.mathworks.com/help/techdoc/ref/cat.html) 。
您还可以通过其他几种方式来执行此操作。首先,您可以先制作整个向量,然后为不需要的元素建立索引并删除它们(即,将它们设置为空向量[] ):
a = 1:20; %# The entire vector a(6:10) = []; %# Remove the elements in indices 6 through 10 您也可以使用set操作 (http://www.mathworks.com/help/techdoc/ref/f16-42340.html#f16-7121)来执行此操作 (http://www.mathworks.com/help/techdoc/ref/f16-42340.html#f16-7121) ,例如功能SETDIFF (http://www.mathworks.com/help/techdoc/ref/setdiff.html) :
a = setdiff(1:20,6:10); %# Get the values from 1 to 20 not including 6 to 10
更多&回答... (https://stackoverflow.com/questions/3729167)
1 2 3 4 5 11 12 13 14 15 16 17 18 19 20 因此,我尝试:
a = 1:5,11:20 但这没用。
我还想以一种非硬编码的方式执行此操作,以便缺少的5个元素可以从任何索引处开始。
回答:
对于您的示例,您需要使用方括号 (http://www.mathworks.com/help/techdoc/ref/specialcharacters.html)来连接两个行向量:
a = [1:5 11:20]; 或减少其硬编码:
startIndex = 6; %# The starting index of the 5 elements to remove a = [1:startIndex-1 startIndex+5:20]; 您可能还需要检查以下相关功能: HORZCAT (http://www.mathworks.com/help/techdoc/ref/horzcat.html) , VERTCAT (http://www.mathworks.com/help/techdoc/ref/vertcat.html) , CAT (http://www.mathworks.com/help/techdoc/ref/cat.html) 。
您还可以通过其他几种方式来执行此操作。首先,您可以先制作整个向量,然后为不需要的元素建立索引并删除它们(即,将它们设置为空向量[] ):
a = 1:20; %# The entire vector a(6:10) = []; %# Remove the elements in indices 6 through 10 您也可以使用set操作 (http://www.mathworks.com/help/techdoc/ref/f16-42340.html#f16-7121)来执行此操作 (http://www.mathworks.com/help/techdoc/ref/f16-42340.html#f16-7121) ,例如功能SETDIFF (http://www.mathworks.com/help/techdoc/ref/setdiff.html) :
a = setdiff(1:20,6:10); %# Get the values from 1 to 20 not including 6 to 10
更多&回答... (https://stackoverflow.com/questions/3729167)