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

2 次查看(过去 30 天)
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

采纳的回答

Walter Roberson
Walter Roberson 2020-3-8
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 个评论
Walter Roberson
Walter Roberson 2020-3-8
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 2020-3-8
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Large Files and Big Data 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by