How do I pad the middle of an array?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Amanda Beatty
am 6 Apr. 2021
Kommentiert: Amanda Beatty
am 9 Apr. 2021
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:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/575027/image.png)
How I want it to be:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/575032/image.png)
0 Kommentare
Akzeptierte Antwort
DGM
am 7 Apr. 2021
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 Kommentare
DGM
am 7 Apr. 2021
Bearbeitet: DGM
am 7 Apr. 2021
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)'
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!