【问题标题】:arrays and loops in matlabmatlab中的数组和循环
【发布时间】:2018-09-06 23:25:36
【问题描述】:

我有一个 matlab 脚本,我在其中尝试从文件 globalbathy.dat 中的数组读取数据。现在我想制作一个脚本,该脚本将根据用户输入读取数组的一部分。因此,根据用户输入,脚本应该能够从数组 A[j,i] 中获取值,其中 i 分量是从 260 到 300,j 是从 50 到 0。下面是脚本示例:

function [lat_sub,lon_sub,depth_sub] = compute_data(coord,dx,dy)

lats = coord(1);
lons = coord(2);
late = coord(3);
lone = coord(4);

latss = lats;
lonss = lons;
lates = late;
lones = lone;

lat_sub = [latss:dy:lates];
lon_sub = [lonss:dx:lones];

Nx = length(lon_sub);
Ny = length(lat_sub);

Nb=Ny*Nx;


filename = 'globalbathy.dat';
delimiterIn = ' ';
headerlinesIn = 1;
A = importdata(filename,delimiterIn,headerlinesIn);

startlon = uint64(((80 - latss)*360) + lonss);
startlat = uint64((80 - latss));

endlon  = uint64(startlon+Nx);
endlat = uint64(startlat+Ny);

for i = startlon:endlon
   for j = startlat:endlat
     printf('i is %d and j is %d\n',i,j);
     disp(A.data(j,i));
   end;
 end;
 return;

但是,当运行脚本时,我收到以下错误:

error: A(0,_): subscripts must be either integers 1 to (2^31)-1 or logicals
error: called from
    compute_data at line 51 column 3

我的印象是 i 和 j 是整数。您如何解决这种情况,以便我获得我想要的数组 A 的值?

【问题讨论】:

  • 是的,整数必须严格大于0。
  • 你不需要强制转换为整数类型来索引,你可以使用普通的双精度数。但它们的值不能有小数部分。您的问题是您尝试索引不存在的元素 0。

标签: arrays matlab loops


【解决方案1】:

是的,ij 必须是整数。

您可以使用floor 函数将ij 的值近似为整数(例如,floor(0.1)0floor(0.9) 也是0):

for i = floor(startlon):floor(endlon)
    for j = floor(startlat):floor(endlat)
        printf('i is %d and j is %d\n',i,j);
        disp(A.data(j,i));
    end
end

【讨论】:

  • OP 已将索引转换为uint64,因此floor 不会做任何事情。 OP 的问题是使用 0 来索引,而索引从 1 开始。
  • 你是对的。我不明白为什么需要uint64 转换
  • A 是一个可使用整数索引的数组。我不明白索引ij 与它有什么关系。
  • 您可能希望将这些问题作为问题的 cmets 提出,以便 OP 得到通知。
猜你喜欢
  • 2014-11-17
  • 2011-06-05
  • 2013-06-20
  • 2013-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-23
相关资源
最近更新 更多