フィルターのクリア

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

2 ビュー (過去 30 日間)
Preyanka Dey
Preyanka Dey 2020 年 3 月 8 日
コメント済み: Preyanka Dey 2020 年 3 月 8 日
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 Center および File ExchangeLarge 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