我试图在一个长字符串中得到一个特定值的平均值,但是我想不出如何从字符串的中间提取一个值。我想从这个字符串和其他字符串中提取出27,然后添加它们。
2015年-10-1,33,27,20,29,24,20,96,85,70,30.51,30.40,30.13,10,9,4,10,6,,T,5,雪,35 2015-10-1,33,27,20,29,24,20,96,85,70,30.51,30.40,30.13,10,9,4,10,6,,T,5,雪,35 2015-10-2,37,32,27,32,27,23,92,80,67,30.35,30.31,30.28,10,10,7,7,4,,T,8,雨-雪,19 2015-10-3,39,36,32,35,33,29,100,90,79,30.30,30.17,30.11,10,7,0,8,3,,0.2,8,雾-雨,13 2015-10-4,40,37,34,38,36,33,100,96,92,30.23,30.19,30.14,2,1,0,6,0,,0.13,8,雾-雨,27 2015-10-5,46,38,30,38,34,30,100,91,61,30.19,30.08,29.93,10,7,0,6,2,,T,6,雾-雨,23
fid = fopen('MonthlyHistory.html');
for i=1:2
str = fgets(fid);
c = strsplit(str,',');
mean=mean+c;
end
fprintf('Average Daily Temperature: %d\n',mean);发布于 2015-12-01 04:44:32
方法1:使用可读的
我猜这是从地下的天气里拉出来的?以你的csv文件为例,确保它是以.csv结尾保存的。那么我要做的是:
my_data = readtable('MonthlyHistory.csv');这会将整个文件读入非常方便的table变量类型。然后你就可以:
average_daily_temp = my_data.MeanTemperatureF; %or whatever it is called in the table我发现表格是记录表格数据的一种非常方便的方法。(加上可读性很好)。
方法2:继续你的方法.
fid = fopen('mh2.csv');
str = fgets(fid); % May need to read off a few lines to get to the
str = fgets(fid); % numbers
my_data = []; %initialize an empty array
while(true)
str = fgets(fid); % read off a line
if(str == -1) % if str is -1, which signifies end of file
break; %exit loop
end
ca = strsplit(str,','); % split string into a cell array of strings
my_data(end+1,:) = str2num(ca{3}); % convert the 3rd element to a number and store it
end
fclose(fid);现在,my_data是一个包含每一行第三个元素的数组。
发布于 2015-12-01 04:36:08
您可以使用textscan,您也可以使用它简化代码,但是对于单个字符串,它的工作方式如下:
S='2015-10-1,33,27,20,29,24,20,96,85,70,30.51,30.40,30.13,10,9,4,10,6,,T,5,Snow,35'
T=textscan(S,'%s','Delimiter',',')
str2double(T{1}{3}) %// the value we want is the 3rd fieldhttps://stackoverflow.com/questions/34012572
复制相似问题