How to grab and process values from a .csv file using fgetl and sscanf?

9 views (last 30 days)
Can anyone please help me:
The attached assignment6.csv file contain 3 columns. I want to read, process and store the values line by line inside 4 vectors. Values from first and third column will remain as it is. However, after reading a number from second column I want pass it through a loop, and then store it into two vectors. When, I applied 'fgetl' it returns first line 2008, 1, 0. However, I can't grab the values after comma. The output should be like the following:
[y m d p] =
2008 1 1 0 % first line
2008 1 2 2 %2nd line
2008 1 3 0 %3rd line
...............................
2008 2 26 17 %2nd last line
2008 2 27 0 %last line
function [y, m, d, p] = convert_date()
fid = fopen('assignment6.csv', 'r');
y = [];
d = [];
m = [];
p = [];
for i = 1:58
tline = fgetl(fid);
out = sscanf(tline, '%d %d %d');
y1 = out(1);
d1 = out(2);
p1 = out(3);
if (fix(d1/30)==0)
m1 = 1
d = d1
elseif (fix(d1/30)== 1)
m1 = fix(d1/30) + 1
d = (d1 - 31)
end
y = [y; y1];
m = [m; m1];
d = [d; d1];
p = [p; p1];
disp ([y m d p])
end
end

Accepted Answer

Walter Roberson
Walter Roberson on 8 Mar 2020
out = sscanf(tline, '%d %d %d');
Your input lines have commas in them. You should put the commas into the format:
out = sscanf(tline, '%d,%d,%d');
  3 Comments
Walter Roberson
Walter Roberson on 8 Mar 2020
It works for me when I test. However a few lines later you have a bug
if (fix(d1/30)==0)
m1 = 1
d = d1
elseif (fix(d1/30)== 1)
m1 = fix(d1/30) + 1
d = (d1 - 31)
end
The problem with that is that d is your variable that is accumulating all of the day-of-the-month information, and you are overwriting it with a scalar.
Preyanka Dey
Preyanka Dey on 8 Mar 2020
Thanks Walter Roberson for your time and patience. You are right. It is taking and processing values after comma, but not returning those in the matrix. Actually, I don't know much about syntax in Matlab. That's why I often face problems when I try to write code. Can you please suggest me any good books of Matlab? My focus is to deal with big data analysis using Matlab. Thank you.

Sign in to comment.

More Answers (0)

Categories

Find more on Large Files and Big Data in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!