# How to create empty indexes when not available?

8 ビュー (過去 30 日間)
Dc215905 2021 年 5 月 21 日

For example:
Say:
data = [2,3,4,5,3,2,4,5]
I want to only look at a subset of the data starting from the 5th index +/-2 of data:
window = data(5-2:5+2)
window =
4 5 3 2 4
That works no problem because the data exisit.
Now say I want to look a the data starting from the 5th index -10/+2
window = data(5-10:5+2)
window = 'Array indices must be positive integers or logical values.'
Since there are not 10 indices available before the 5th index this won't work.
Is there a way to automatically fill indexes that don't exist with 'NaN' and fill the rest do the final output would look something like:
window =
NaN NaN NaN NaN NaN NaN 2 3 4 5 3 2 4
Any help would be greatly appreciated.
Thanks!

サインインしてコメントする。

### 採用された回答

Stephen23 2021 年 5 月 21 日

data = [2,3,4,5,3,2,4,5];
x = 5;
n = 10;
p = 2;
window = data(max(1,x-n):min(end,x+p))
window = 1×7
2 3 4 5 3 2 4
Are the NaNs really required?
##### 2 件のコメント表示 1 件の古いコメント非表示 1 件の古いコメント
Stephen23 2021 年 5 月 21 日

Just pad the NaNs to the ends:
data = [2,3,4,5,3,2,4,5];
x = 5;
n = 10;
p = 2;
window = data(max(1,x-n):min(end,x+p))
window = 1×7
2 3 4 5 3 2 4
window = [nan(1,1+n-x),window,nan(1,x+p-numel(data))]
window = 1×13
NaN NaN NaN NaN NaN NaN 2 3 4 5 3 2 4

サインインしてコメントする。

### カテゴリ

Find more on Matrix Indexing in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by