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