我正在从URL中读取数据,解析它,然后尝试进一步格式化数据:
year = 2008;
month = 9;
day = 30;
raw = urlread(sprintf('http://www.wunderground.com/history/airport/KCVS/%i/%i/%i/DailyHistory.html?HideSpecis=0&theprefset=SHOWMETAR&theprefvalue=0&format=1',year,month,day));
data = textscan(raw,'%s %s %s %s %s %s %s %s %s %s %s %s','Delimiter',',','HeaderLines',2,'CollectOutput',true);
dir = data{1}(1:end-1,7);
wind = cellfun(@str2num,data{1}(1:end-1,8),'UniformOutput',false);
gust = cellfun(@str2num,data{1}(1:end-1,9),'UniformOutput',false);
wind{cellfun(@isempty,wind)} = 0;
gust{cellfun(@isempty,gust)} = 0;
现在wind{cellfun(@isempty,wind)} = 0;
可以正常工作gust{cellfun(@isempty,gust)} = 0;
但是我得到的错误是: ???此分配的右侧值太少,无法满足左侧。 cellfun(@isempty,gust)
正确返回逻辑数组。 gust{1} = 0
也可以。 为什么它适用于风而不是阵风?
答案 0 :(得分:5)
这是一种更好的解析数据的方法:
year = 2008; month = 9; day = 30;
%# get raw data
urlStr = sprintf('http://www.wunderground.com/history/airport/KCVS/%i/%i/%i/DailyHistory.html?HideSpecis=0&theprefset=SHOWMETAR&theprefvalue=0&format=1',year,month,day);
raw = urlread(urlStr);
%# collect data and headers
raw = strrep(raw, '<br />', ''); %# remove HTML <br/> at end of each line
raw = textscan(raw,repmat('%s ',1,12), 'Delimiter',',', 'HeaderLines',1, 'CollectOutput',true);
headers = raw{1}(1,:);
data = raw{1}(2:end-1,:);
%# extract certain columns
A = data(:,7); %# cell array of strings
B = str2double(data(:,8:9)); %# numeric data
B( isnan(B) ) = 0;
其中:
>> B
B =
5.8 0
5.8 0
5.8 0
0 0
0 0
5.8 0
4.6 0
0 0
3.5 0
4.6 0
6.9 0
9.2 17.3
12.7 20.7
13.8 19.6
15 0
11.5 0
11.5 0
9.2 0
8.1 0
9.2 0
9.2 0
9.2 0
10.4 0
10.4 0
答案 1 :(得分:4)
wind{cellfun(@isempty,wind)}
工作但gust{cellfun(@isempty,wind)}
不起作用的原因仅仅是风恰好只有一个非空元素。至于真正的问题,用大括号索引一个单元格数组会返回索引的单元格的元素;当与非标量索引(例如逻辑数组)一起使用时,您基本上一次返回一个元素的值(您可以看到ans
变量被覆盖了33次)。相反,您必须使用括号来索引数组,即返回单元格数组的单元格,并使用包含所需内容的单元格覆盖数组元素 - 单元格。因此
wind(cellfun(@isempty,wind)) = {0};
gust(cellfun(@isempty,gust)) = {0};
答案 2 :(得分:1)
大括号有所不同:
wind(cellfun(@isempty,wind)) = {0};
gust(cellfun(@isempty,gust)) = {0};
摘自Cell Arrays and Their Contents
使用卷曲 用于设置或获取的大括号{} 单元格数组的内容。
使用括号()索引到a 用于收集子集的单元数组 细胞聚集在另一个细胞阵列中。