PDA

查看完整版本 : Matlab中单元逻辑索引的问题


poster
2019-12-10, 20:48
我正在从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也将起作用。 为什么它对风有效但对阵风无效?



回答:

wind{cellfun(@isempty,wind)}有效但gust{cellfun(@isempty,wind)}并不简单,因为wind恰好只有一个非空元素。至于真正的问题,用大括号索引一个单元格数组将返回被索引的单元格的元素。当与非标量索引(例如逻辑数组)一起使用时,本质上您将返回每个元素的值,一次返回一个(您可以看到ans变量被覆盖33次)。取而代之的是,您必须使用括号对数组建立索引,即返回单元格数组的单元格,并用包含所需内容的单元格覆盖数组的元素(即单元格)。因此

wind(cellfun(@isempty,wind)) = {0}; gust(cellfun(@isempty,gust)) = {0};

更多&回答... (https://stackoverflow.com/questions/3816752)