在每行更改变量的情况下构建矩阵的问题

时间:2020-01-17 02:29:53

标签: matlab for-loop matrix

我正在尝试对要在数据集中定义的多边形的4个点进行循环。我使用lat,lon,dlat和dlon来说明这些观点

lat = [35.314166 35.413909 35.533307 35.751982 35.3142 35.1607 35.0475 34.9878 34.9441];
lon = [-119.865953 -119.970299 -120.086757 -120.300046 -119.8659 -119.7068 -119.5583 -119.4711 -119.4029];

dlat = 0.524893450440127;
dlon = 0.73025079017917;

首先,我想做一个循环以创建4个点并将它们保存为大小为(4,4)的矩阵b的第一行

这是我需要的矩阵

b = [p11 p12 p13 p14 ;
     p21 p22 p23 p24 ;
     p31 p32 p33 p34 ;
     p41 p42 p43 p44]  

以下是我想定义的前两个多边形点的示例:

 p11 = [lon(9) + dlon, lat(9) + dlat]
 p12 = [lon(8) + dlon, lat(8) + dlat]
 p13 = [lon(8) - dlon, lat(8) - dlat]
 p14 = [lon(9) - dlon, lat(9) - dlat]

 p21 = [lon(8) + dlon, lat(8) + dlat]
 p22 = [lon(7) + dlon, lat(7) + dlat]
 p23 = [lon(7) - dlon, lat(7) - dlat]
 p24 = [lon(8) - dlon, lat(8) - dlat]

我对定义此for循环感到困惑,我什至不知道解决方案是否为for循环。请帮我。谢谢!

1 个答案:

答案 0 :(得分:0)

这是两种解决方案。我试图尽可能地靠近您向我展示的非循环代码的地方:

s=numel(lon); % I guess we start at 9 because lon has 9 elements?
b=zeros(4,4,2);
for ix=1:size(b,1)
    %Calculate the indices of lon and lat
    index=s-ix;
    %very similar to the example you showed, insert the data into the
    %matrix
    b(ix,1,:)=[lon(index+1) + dlon, lat(index+1) + dlat];
    b(ix,2,:)=[lon(index)   + dlon, lat(index)   + dlat];
    b(ix,3,:)=[lon(index)   - dlon, lat(index)   - dlat];
    b(ix,4,:)=[lon(index+1) - dlon, lat(index+1) - dlat];
end

这里是一种可减少代码量的替代方法。

s=numel(lon); % I guess we start at 9 because lon has 9 elements?
b=zeros(4,4,2);
for ix=1:size(b,1)
    %Calculate the indices of lon and lat
    index=s-ix+[1,0,0,1];
    %Build up one slice
    h=([lon(index);lat(index)]+[dlon;dlat].*[1,1,-1,-1]).';
    %insert h into the matrix. h is wrong way round, so it is transposed.
    b(ix,:,:)=h.';
end