Info

此问题已关闭。 请重新打开它进行编辑或回答。

Could someone please tell me what I'm doing wrong.

1 次查看(过去 30 天)
I'm using a recursive function to remove missing data from a dataset x. But the result that I'm getting is the same as the input matrix even when there is missing data. Whenever there is a missing data in my velocity(2nd column of my matrix), ie.,a NaN, I want to delete those data points from the nearest zero velocity before the missing point to the zero after which a non-zero value occurs.
if true
function r = no_vel_miss( x ) %x is my matrix with all data-time and vel as columns
i=1;
flag=0;
for l=1:length(x(:,1))
if isnan(x(l,2)) %checking if the value in velocity is NaN
flag=1;
break;
end
end
if flag==0
r=x; %if there is no missing point, return the matrix
else
while i<=length(x(:,1))
if isnan(x(i,2))
for j=i:-1:1
if x(j,2)==0
prezero=j; %prezero is the nearest zero velocity before missing point
break;
end
end
for j=i:length(x(:,1))
if x(j,2)==0&&x(j+1,2)~=0
postzero=j; %postzero is the nearest zero velocity after which a non-zero velocity occurs
break;
end
end
x_1=cat(1,x(1:prezero,:),x(postzero:length(x(:,1)),:)); %here I'm removing all that data near the missing point as mentioned above
i=prezero;
r=no_vel_miss(x_1);
else
i=i+1;
end
end
end
end
end
  1 个评论
Jan
Jan 2018-6-18
编辑:Jan 2018-6-18
When the posted function does not do what you want, and you do not explain it also, how could we guess how to fix the code? Please edit the question and post the purpose of the code.
A bold guess: If the first column of x contains a NaN, crop all surrounding rows, which contain 0 in the second column. Correct?

回答(1 个)

Jan
Jan 2018-6-18
编辑:Jan 2018-6-18
Although I do not understand, what the code should do, this looks strange:
i = 1;
flag = 0;
for l = 1:length(x(:,1))
if isnan(x(i,2))
flag = 1;
break;
end
end
This is a loop over "l" (lowercase L), but the body of the loop depends on "i". Is this a typo?
What about omitting the loop and using:
flag = any(isnan(x(:, 2)));
  2 个评论
Nagesh A P
Nagesh A P 2018-6-18
Thanks. That was a typo. Also, do recursive functions take so much time to execute?
Jan
Jan 2018-6-18
Yes, calling the function recursively consumes a lot of memory, because you duplicate large parts of the input array in each call. But this is not useful here at all. A simpler non-recursive version:
function r = no_vel_miss(x)
keep = true(size(x, 1));
miss = find(isnan(x(:, 2))).';
x0 = find(x(:, 2) == 0);
for k = miss
index = find(k > x0, 1);
keep(x0(index)+1:x0(index + 1)-1) = false;
end
r = x(keep, :);
end
I'm not sure if this does exactly, what you want. But it should clarify how to simplify your code.

此问题已关闭。

Community Treasure Hunt

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

Start Hunting!

Translated by