Delete every nth element in array and increasing 1 NaN value per new row
8 views (last 30 days)
Show older comments
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 Comments
Answers (3)
Joe Vinciguerra
on 27 Jun 2023
Edited: Joe Vinciguerra
on 27 Jun 2023
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 Comments
Fangjun Jiang
on 27 Jun 2023
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 Comments
Jan
on 27 Jun 2023
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 Comments
See Also
Categories
Find more on Logical 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!