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

조회 수: 4 (최근 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에서 Entering Commands에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by