Turn a row vector with -99 separating data sets into a matrix
Show older comments
Some experience with Matlab, but a complete newcomer to the programming aspect. Trying to teach myself a bit with the Stormy Attaway book.
One of the problems in the while loops section is to read data from a file containing a single row vector of data with data sets separated by a flag -99, create a new vector that only has data values up to but not including the -99, and plot the values. That code looks like this:
load experd.dat
i = 1;
while experd(i) ~= -99
newvec(i) = experd(i);
i = i + 1;
end
plot(newvec,'ko')
xlabel('Reading #')
ylabel('Weight(pounds)')
title('First Data Set')
I wanted to modified the code a bit to plot the values after the -99 as well so I wrote the following:
load experdata.txt
i = 1;
while experdata(i) ~= -99
newvec1(i) = experdata(i);
i = i+1;
end
plot(newvec1, 'o')
xlabel('Reading #')
ylabel('Weight (pounds)')
title('First data set')
hold on
i = i+1;
[m,n] = size(newvec1);
[r,c] = size(experdata);
while i <= c
newvec2(i-(n+1)) = experdata(i-(n+1));
i = i+1;
end
plot(newvec2, '*')
xlabel('Reading #')
ylabel('Weight (pounds)')
title('First data set')
But, then I thought it would be nice to modify the code to handle a case in which there are an unknown number of data sets separated by -99s. I started to write the following, which kind of works but doesn't give me exactly what I would like.
load experdata.txt
[m,n] = size(experdata);
i = 1;
x = 1;
while i <= n
if experdata(i) ~= -99
newvec(x,i) = experdata(i);
i = i+1;
else
i = i+1;
x = x+1;
end
end
The problem is that you get a matrix that looks like
1 2 3 4 0 0 0 0
0 0 0 0 5 6 7 8
where there original data would have been 1 2 3 4 -99 5 6 7 8,
whereas I would prefer
1 2 3 4
5 6 7 8
The problem is that I can't figure out how to reset the index when the code passes over the -99.
Any insight would be greatly appreciated. Thank you. Nate
1 Comment
Image Analyst
on 29 Apr 2017
You'd get more attention if people could try your code. Attach experdata.txt.
Answers (1)
Andrei Bobrov
on 29 Apr 2017
out = zeros(size(experdata));
l0 = experdata == -99;
ii = find(l0)+1;
out([1,ii]) = 1;
out = cumsum(out(~l0));
out_main = accumarray(out(:),experdata(~l0),[],@(x){x});
Categories
Find more on Guidance, Navigation, and Control (GNC) 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!