MATLAB Answers

How to read rows until I find blank row in csv file and copy to another cell?

4 views (last 30 days)
Gopal Pande
Gopal Pande on 19 Sep 2020
Commented: Walter Roberson on 22 Sep 2020
I have .csv file with data.after few rows there are blank rows, blank row can be after 2 rows or after 5 rows or maybe after 150 rows it's not fixed. I wanted to copy data until find blank row and create seperate cell to use it further and do same with next rows of data until I find next blank row. Stuck with logic, tried using readmatrix(filename), tried detecting blank row from 'NaN' string Not able to solve this problem..

  0 Comments

Sign in to comment.

Answers (2)

Vasishta Bhargava
Vasishta Bhargava on 19 Sep 2020
Edited: Walter Roberson on 19 Sep 2020
fid = fopen('C:\path\file.csv', 'rt');% opens the file in text mode
numdata = textscan(fid,'%f %f....', 'headerlines', 1, 'delimiter', ',');
fclose(fid);

  2 Comments

Vasishta Bhargava
Vasishta Bhargava on 19 Sep 2020
fid = fopen('C:\path\file.csv', 'rt');% opens the file in text mode
numdata = textscan(fid,'%f %f....', 'headerlines', 1, 'delimiter', ',');
numdata(numdata == NaN) = [];
fclose(fid)
Gopal Pande
Gopal Pande on 19 Sep 2020
I would like to add more description here,
my csv file has data with size Eg. [1853 * 152] (rows,columns)
There is one blank row only and after that i will have my data to read and copy to another cell. position or row number is not fixed.
Eg. first two rows I have data then third row is blank row
next I may have data in 153 rows and next is blank row
next i may have data in 12 rows and then blank row.
I want to copy data into another cell until i find first blank row, then i want to copy next data into another cell until there is next blank row.
my data is can be sorted lets say by detecting blank row and need to copy data evrytime in new cell array/matrix

Sign in to comment.


Walter Roberson
Walter Roberson on 19 Sep 2020
Edited: Walter Roberson on 19 Sep 2020
d = readmatrix(filename)
mask = any(isnan(d), 2).';
starts = findstr([false, mask], [0,1]);
stops = findstr([mask, false], [1,0]);
blocks = arrayfun(@(s,e)d(s:e,:), starts, stops, 'uniform', 0);

  6 Comments

Show 3 older comments
Walter Roberson
Walter Roberson on 19 Sep 2020
Darn, I am having trouble with the mobile interface.
The a in that line should be any
Gopal Pande
Gopal Pande on 22 Sep 2020
New lines of code works better than previous.
But in blocks var blank row is getting copied into another cell, I want to copy data and not blank row which can be seperated/identified by NaN.
But thanks anyway, i am also debugging this code further to get what is intended...

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by