如何修复Matlab中color_post函数的数组越界等错误?
问题:调用color_post函数时出现索引越界错误
所用数据
lon = [121,1.212500000000000e+02,1.215000000000000e+02,1.217500000000000e+02,122]; lat = [10,10.250000000000000,10.500000000000000,10.750000000000000,11]; bdlvl = [0,1,2,3,4];
报错情况
调用color_post(lon, lat, bdlvl, [])时触发错误:
Index in position 1 exceeds array bounds. Index must not exceed 1
错误指向代码行:
item=floor((1+var(ibb2(i),1)-a)/(b-a)*63);
color_post函数代码
function color_post(lon,lat,var,limit) % mapping z values with gradient of colors % make sure you have set your projection area already m=length(var); hold on load('C:\Users\Pia\Downloads\scripts\MyRainbowCmap.mat') cmap=mycmap; if isempty(limit)==1; a = min(var); b = max(var); else a = limit(1); b=limit(2); end caxis([a b]); hold on var(imag(var) ~= 0) = NaN; ibb2 = find(isfinite(var)); %for i=length(ibb2):-1:1; for i=1:length(ibb2); item=floor((1+var(ibb2(i),1)-a)/(b-a)*63); if(item<1) item=1; end if(item>64) item=64; end m_plot(lon(ibb2(i)),lat(ibb2(i)),'o','color',cmap(item,:),'markerfacecolor',cmap(item,:),'MarkerSize',7); end fig=gcf; set(fig,'Colormap',mycmap); %h=colorbar;
问题原因
传入的bdlvl是行向量,但代码中用var(ibb2(i),1)按「行索引+列索引」的方式取值。当var是行向量时,它只有1行,ibb2(i)的取值是2到5(对应有效数据的位置),此时var(ibb2(i),1)会试图访问第ibb2(i)行第1列,超出了行向量的行范围(仅1行),因此触发索引越界错误。
另外你尝试把循环起始值改成i=0是错误的,MATLAB的索引从1开始,i=0会导致后续访问ibb2(0)时再次触发索引错误。
解决方法
- 修正取值方式:将报错行的
var(ibb2(i),1)改为var(ibb2(i)),单索引方式可以兼容行向量和列向量的取值:item=floor((1+var(ibb2(i))-a)/(b-a)*63); - 恢复正确的循环起始值:把
for i=0:length(ibb2);改回for i=1:length(ibb2); - (可选)如果需要更鲁棒的代码,可以在函数开头添加一行,将
var统一转为列向量:var = var(:);
修改后重新调用color_post(lon, lat, bdlvl, [])即可实现床层值的颜色分类。
内容的提问来源于stack exchange,提问作者Sofia Joy Quillope
相关产品推荐
相关产品推荐

