How to write rows to a csv based on the preceding data?

1 view (last 30 days)
If I have an array:
  • 1 3
  • 2 1
  • 3 7
  • 4 6
  • 5 8
  • 7 3
  • 8 2
how could I write a row between 5 and 7 that says '6 0' in a csv? And, how could I do this without having to go through and find that point? So, if I had the forth row missing it would fill the same way (meaning '4 0')?

Accepted Answer

Image Analyst
Image Analyst on 2 Feb 2015
What's wrong with finding the "missing" row? If you don't then you can't do what you say. This code works:
m=[...
1 3
2 1
3 7
4 6
5 8
7 3
8 2]
outputRows = max(m(:, 1))
inputRow = 1;
output = [];
for outputRow = 1 : outputRows
fprintf('Processing row #%d\n', outputRow);
% Get this input number from this row.
thisNumber = m(inputRow, 1);
if thisNumber == outputRow
% It matches.
output = [output; m(inputRow,:)];
inputRow = inputRow + 1;
else
output = [output; outputRow, 0];
end
end
% Display output in command window.
output

More Answers (1)

dpb
dpb on 2 Feb 2015
To find the missing unless you have some other a priori knowledge (why it's missing, say) that is useful to find the location then, "No, Virginia, there is no Santa Claus". IOW, there is no free lunch. It is, however, relatively easy to find the missing location in a sequence, simply look for the difference that isn't fixed...
>> x=[1:5 7:10]; % the series
>> find(diff(diff(x))>0)+2
ans =
6
>>
The "trick" is that the second difference of a linear trend is zero; if the trend is +-ive then the first difference that is off is also positive. The +2 simply corrects for the "one-off" difference in length of each difference compared to the original.
Unfortunately, a csv file is sequential; the only practical way to write it with the updated information is to rewrite it entirely once you've made the correction in memory.

Community Treasure Hunt

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

Start Hunting!