Replace elements from a matrix with NaN and add new columns
Show older comments
Hello people, I have a MATLAB question about replacing certain elements in a matrix with NaN values and adding some new columns to the Matrix. I have a 64504x181 matrix. Not all columns have the same length, for shorter columns, NaN values are added till the end. Now I would like to remove certain elements from each column. I have identified the start and end indices of the elements I would like to remove. E.g. in the first column I would like to replace elements from 608 to 12128 with NaN and take all the elements from 12129 till the end into column 2 (and so, column 2 would become column 3). This is the piece of code I have so far, I am not sure how to go on from there.
ExcludePeriods is 12x2 matrix, column 1 is starting time and column 2 is end time of the data I want to exclude.
data is the matrix I want to modify, and Times is a matrix with the same size, that contains the time of each entry in data.
for i=1:size(ExcludePeriods,1)
[ExcludeIndST(1,1),ExcludeIndST(1,2)] = find(Times == ExcludePeriods(i,1));
[ExcludeIndET(1,1),ExcludeIndET(1,2)] = find(Times == ExcludePeriods(i,2));
if ExcludeIndST(1,2) == ExcludeIndET(1,2)
data((ExcludeIndST(1,1):ExcludeIndET(1,1)),ExcludeIndST(1,2)) = NaN;
else
data((ExcludeIndST(1,1):End),ExcludeIndST(1,2)) = NaN;
data((1:ExcludeIndET(1,1)),ExcludeIndET(1,2)) = NaN;
end
end
Thank you in advance!
4 Comments
JohnGalt
on 1 Nov 2018
As a rule, it's generally a bad idea to add columns without pre-allocating space... that is - it's better to start out by making a matrix the right size and then updating the elements with the desired values.
also - if you make a more basic example with some actual numbers it would be easier to help...
Additionally, you can uses 'logical indexing' to simplify your code... e.g.
a = 1:10
a(a>5 & a< 9)=nan % set values greater then 5 and less than 9 to nan
and doing something similar to a matrix:
i = 1;
a = magic(5)
a(a(:,i)>5 & a(:,i)<12,i)=nan
Ghazi Eltiti
on 1 Nov 2018
Edited: Ghazi Eltiti
on 1 Nov 2018
Image Analyst
on 1 Nov 2018
Attach your matrix in a .mat file, and then people might start working on code to help you.
Ghazi Eltiti
on 1 Nov 2018
Answers (0)
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!