Delete every nth element in array and increasing 1 NaN value per new row
조회 수: 22 (최근 30일)
이전 댓글 표시
Dear,
I have a array of the following numbers.
Array = [1,2,3,4,5,6,7,8,9,10]
To make an sensitivity analysis, I need to 'delete' datapoints and replace them for NaN's increasing for every row. So for the second row every 2nd number needs to be a NaN value, the thrid row every 3rd number needs to be a NaN value. etc. This looks the following:
Array = [1,NaN,3,NaN,5,NaN,7,Nan,9,NaN;
1,NaN,NaN,4,NaN,NaN,7,NaN,NaN,10;
1,NaN,NaN,NaN,5,NaN,NaN,NaN,9,NaN]
This needs to continue for the next 15 (depending on the outcome so another variable:)) rows where for every new row 1 more nan value replaces a value. The NaN replaces a value and is not inserted and therefore the length of the rows are not changing. I found these two examples that are the answer for one row and here the same answer:
x(2:2:end) = nan;
This works for perfectly for 1 new row however I cannot seem to get it working for multiple rows with a loop. What i've (incorrectly) made is this:
% Compute the number of rows
numRows = 15;
numCols = numel(OriginalArray);
% Create a new array with the specified number of rows and columns
newArray = zeros(numRows, numCols);
% Assign the original 'OriginalArray' to the first row
newArray(1, :) = OriginalArray;
%Set NaN with increasing steps to replace values with NaN
for row = 2:numRows
newArray(row, :) = newArray(row-1, :);
NaN_indices = 2:row+1:numel(OriginalArray)+row-1;
newArray(row, NaN_indices) = NaN;
end
Could I pick some brains and you would help me out massively.
댓글 수: 0
채택된 답변
Jan
2023년 6월 27일
Array = [1,2,3,4,5,6,7,8,9,10];
n = numel(Array);
Out = nan(n - 2, n);
for k = 2:n - 1
Out(k-1, 1:k:n) = Array(1:k:n);
end
Out
댓글 수: 0
추가 답변 (2개)
Joe Vinciguerra
2023년 6월 27일
편집: Joe Vinciguerra
2023년 6월 27일
Here's how I would do it:
[EDIT: misunderstood the disired result. HERE'S how I would do it...]
OriginalArray = 1:10;
numRows = 15;
numCols = numel(OriginalArray);
newArray = repmat(OriginalArray, numRows, 1);
for i = 1:numRows
j = zeros(1,10);
j(1:i+1:numCols) = 1;
newArray(i, j==0) = NaN;
end
newArray
댓글 수: 0
Fangjun Jiang
2023년 6월 27일
nRow=15;
nCol=10;
Array=repmat(1:nCol,nRow,1);
for k=1:nRow
index=mod((1:nCol),k+1)~=1;
Array(k,index)=nan;
end
Array
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!