Matlab delete's value's from array

조회 수: 1 (최근 30일)
loes visser
loes visser 2016년 10월 12일
댓글: Mischa Kim 2016년 10월 13일
Hi,
I have a code in matlab that generates an big array [3648x1]. This array looks something like:
[NaN
NaN
NaN
NaN
0
0
1
0
1
1
NaN
NaN
NaN
0
0
1
1 ]
I want to replace the zeros with NaN, where after I can delete all the NaN's
This is the code, where variable1 is the [3648x1] array (and a, b, c are also [3648x1] array's);
for a = 0 : (length(variable1)-1);
if variable1(a+1) == 0;
variabele2(a+1) = NaN;
end
end
k = [variabele2, a, b, c];
k(any(isnan(k),2),:)=[];
variabele2 = k(1:end,1);
a = k(1:end,2);
b = k(1:end,3);
c = k(1:end,4);
But after the for loop, the array is reduced to an [1x1656] array. How is this possible? And more important, how can I fix it so the code will do what I want.
  댓글 수: 1
loes visser
loes visser 2016년 10월 13일
The data is time related, thats why I want to delete a whole row when a value in variable1 is NaN or 0. Then I can make new variables were variable1(1) has still the same timestamp as a(1) or b(1).
This code is working with another variable, I dont get why it wouldnt work with this variable and why it is reducing its values.

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

답변 (4개)

Mischa Kim
Mischa Kim 2016년 10월 12일
편집: Mischa Kim 2016년 10월 12일
loes, based on your description, how about
mat(isnan(mat) | mat==0) = [];
where mat is, for example, the matrix you show at the very top.
  댓글 수: 5
Stephen23
Stephen23 2016년 10월 13일
the square brackets are not required:
k(isnan(k(:,1)) | k(:,1)==0,:) = []
Mischa Kim
Mischa Kim 2016년 10월 13일
I like to use them at times to help with readability.

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


Matthew Eicholtz
Matthew Eicholtz 2016년 10월 12일
Suppose you have an M-by-N matrix (A) of NaNs, 0s, and 1s:
M = 3648; % number of rows
N = 4; % number of columns
A = double(rand(M,N)>0.1); % random mix of 0s and 1s
A(rand(size(A))>0.9) = NaN; % randomly add some NaNs
You can create a mask matching the conditions you are looking for (in this case, we only want to keep rows that do not have NaNs or 0s):
mask = all(~isnan(A) & A~=0,2);
Then, grab the rows corresponding to the mask.
B = A(mask,:);

Thorsten
Thorsten 2016년 10월 12일
You remove all rows that contain a NaN in the line
k(any(isnan(k),2),:)=[];
and then you assign the variables
variabele2 = k(1:end,1);
a = k(1:end,2);
b = k(1:end,3);
c = k(1:end,4);
so afterwards the variables are smaller. So what's the problem?

Andrei Bobrov
Andrei Bobrov 2016년 10월 13일
k = [1 20 3 0
NaN 19 2 1.1
NaN 20 1 0.9
NaN 19 2 0.4
0 18 0 0.3
1 19 1 0.8
1 20 3 1.0
0 21 1 1.1
1 22 0 0.7
NaN 18 1 0.5
NaN 19 3 0.9];
out = k(k(:,1)~=0 & ~isnan(k(:,1)),:);

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by