匿名用户
1级
2016-12-17 回答
m = 20;
n = 4;
vec = 1:m;
cou = 0;
pos = zeros(1,n);
while cou < n
tem = round(m*rand)+1;
if ~ismember(tem,pos)
pos(cou+1) = tem;
cou = cou+1;
end
if cou == n
break;
end
end
pos = sort(pos);
pos1 = [1 pos];
pos2 = [pos m+1];
pos3 = pos2-pos1;
pos3(find(pos3 == 0)) = [];
tran = mat2cell(vec,1,pos3);
len = length(tran);
if len == n-1
for i = 1:2:2*n-1
result{i} = [0];
end
for i = 2:2:2*n-1
result{i} = tran{i/2};
end
end
if len == n
if pos(1) == 1
for i = 1:2:2*n
result{i} = [0];
end
for i = 2:2:2*n
result{i} = tran{i/2};
end
else
for i = 1:2:2*n
result{i} = tran{(i+1)/2};
end
for i = 2:2:2*n
result{i} = [0];
end
end
end
if len == n+1
for i = 1:2:2*n+1
result{i} = tran{(i+1)/2};
end
for i = 2:2:2*n+1
result{i} = [0];
end
end
result = cell2mat(result)
追答:
插入数量n可以改,但要少于等于m+1。被插入的向量vec也可以改,注意同时改下向量的维数m。