Matlab delete's value's from array

1 vue (au cours des 30 derniers jours)
loes visser
loes visser le 12 Oct 2016
Commenté : Mischa Kim le 13 Oct 2016
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 commentaire
loes visser
loes visser le 13 Oct 2016
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.

Connectez-vous pour commenter.

Réponses (4)

Mischa Kim
Mischa Kim le 12 Oct 2016
Modifié(e) : Mischa Kim le 12 Oct 2016
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 commentaires
Stephen23
Stephen23 le 13 Oct 2016
the square brackets are not required:
k(isnan(k(:,1)) | k(:,1)==0,:) = []
Mischa Kim
Mischa Kim le 13 Oct 2016
I like to use them at times to help with readability.

Connectez-vous pour commenter.


Matthew Eicholtz
Matthew Eicholtz le 12 Oct 2016
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 le 12 Oct 2016
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 le 13 Oct 2016
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)),:);

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by