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

4 vues (au cours des 30 derniers jours)
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

Réponse acceptée

Walter Roberson
Walter Roberson le 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 commentaires
Walter Roberson
Walter Roberson le 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 le 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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Entering Commands dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by