How do I pad the middle of an array?

3 次查看(过去 30 天)
I have an array that is basically stepped. I want to pad each side of the step with additional numbers (the orange cells). Can you help me figure out how to do this?
Original Array:
How I want it to be:

采纳的回答

DGM
DGM 2021-4-7
For vectors, you can just extrapolate each segment and cat them back together. You'd need to determine where each step is.
a=[1:6 78:82 109:111]'
b=[interp1(a(1:6),1:8,'linear','extrap'), ...
interp1(a(7:11),-1:7,'linear','extrap'), ...
interp1(a(12:14),-1:5,'linear','extrap')]'
gives:
a =
1
2
3
4
5
6
78
79
80
81
82
109
110
111
b =
1
2
3
4
5
6
7
8
76
77
78
79
80
81
82
83
84
107
108
109
110
111
112
113
  3 个评论
DGM
DGM 2021-4-7
编辑:DGM 2021-4-7
Those second vectors specify the new query points. What's confusing is that the short syntax I used is basically using the vector length as "x" so to speak. So it's like doing this:
interp1(1:5,a(7:11),-1:7,'linear','extrap');
so I'm taking a 5-element vector and I'm extrapolating two elements off of either end.
Yeah, you wouldn't want to do that a bunch of times, but the idea is the same. The only hard part about doing it automatically is determining the criteria you're going to use to detect what you consider to be a step. For this example, I'm just going to assume a maximum difference.
clc
a=[1:6 78:82 109:111]'
ps=2; % specify a padsize
% i'm assuming that any increment >1 is considered a discontinuity
a=reshape(a,[1 numel(a)]); % safeguard against vector orientation
discloc=find(diff(a)>1); % find transitions
discloc=[discloc(1) diff([discloc numel(a)])] % find width of chunks
chunks=mat2cell(a,1,discloc); % split vector into subvectors
for c=1:numel(chunks)
% you had chunk 1 padded asymmetrically
% you can also pad the last chunk asymmetrically if you want
if c==1
indexvec=1:(numel(chunks{c})+ps);
else
indexvec=(1-ps):(numel(chunks{c})+ps);
end
chunks{c}=interp1(chunks{c},indexvec,'linear','extrap');
end
b=cell2mat(chunks)'
Amanda Beatty
Amanda Beatty 2021-4-9
@DGM Thank you thank you! This solution is so much more elegant than what I was trying (and failing) to do with interp1.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by