How to create empty indexes when not available?

조회 수: 5 (최근 30일)
Dc215905
Dc215905 2021년 5월 21일
편집: Stephen23 2021년 5월 22일
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
Stephen23 2021년 5월 21일
편집: 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
Dc215905
Dc215905 2021년 5월 21일
편집: Dc215905 2021년 5월 21일
Thanks for the response. Yes, the NaN are necessary ( i think).
I'm trying to apply the answer you gave to the following scenerio.
I have a data set that's 1x1000. I'm allowing users to find specific events within the data and plotting a window around the event. This could result in 100 different event windows for a given dataset. For the most part, the window they choose around an event has data available, but if the event is at the beginning or the end of the data set then they won't be able to group that particular event with the rest of the events because the array lengths won't be similar.
I've thought about using just cells, but my current GUI is written in a way that each event window is stored in the a cell, but the associated x value ('time') is not because it's assumed to be constant depending on the users window definition. Ultimately the user is able to collapse all of the event windows and take the average signal etc. As a result, my current solution is to just fill the empty IDX with NaN so all of the arrays are uniform in length for downstream analysis options.
Stephen23
Stephen23 2021년 5월 21일
편집: Stephen23 2021년 5월 22일
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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Search Path에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by