【问题标题】:Replacing elements on matrix with row/column by row/column用行/列逐行/列替换矩阵上的元素
【发布时间】:2017-06-23 19:53:58
【问题描述】:

我有6 站和来自它的3 不稳定。不稳定的电台uspt 是,比如说2, 3, 6

每个站点代表两列和两行,例如站点 1 对应于第 1 行和第 2 行,站点 2 对应于第 3 行和第 4 行,依此类推。前两列对应于第一个不稳定站,即站 2。接下来的两列(第 3 列和第 4 列)对应于下一个不稳定站,即站 3,依此类推。

我想创建一个矩阵B,它使用上述信息为不稳定点分配编号1,并将零分配给所有其他点。因此,对于给定数量的全站仪和不稳定的全站仪,以下是所需的输出:

B = [0   0   0   0   0   0
     0   0   0   0   0   0
     1   0   0   0   0   0
     0   1   0   0   0   0
     0   0   1   0   0   0
     0   0   0   1   0   0
     0   0   0   0   0   0
     0   0   0   0   0   0
     0   0   0   0   0   0
     0   0   0   0   0   0
     0   0   0   0   1   0
     0   0   0   0   0   1]

这是我尝试过的:

%my input
stn=6;                  %no of stations
us=3;                   %no of unstable stations
uspt=[2 3 6]            %unstable station

m=stn*2;                %size of matrix, no of row
u=(stn)-us;             %no of stable station
n=m-2*u;                %no of column

B = zeros(m,n);
io=uspt(2:2:length(uspt));ie=uspt(1:2:length(uspt));       %ie=even numb/io=odd numb
for ii=numel(B+1,2)
    if ie>0|io>0
        ii=ii+1;
        B(ie*2-1,ii-1)=1;B(ie*2,ii)=1;
        ii=ii+1;
        B(io*2-1,ii)=1;B(io*2,ii+1)=1;
    end
end
B=B

我得到了什么:

B = [0   0   0   0   0   0
     0   0   0   0   0   0
     1   0   0   0   0   0
     0   1   0   0   0   0
     0   0   1   0   0   0
     0   0   0   1   0   0
     0   0   0   0   0   0
     0   0   0   0   0   0
     0   0   0   0   0   0
     0   0   0   0   0   0
     1   0   0   0   0   0
     0   1   0   0   0   0]

23 站的分配正确,6 站的分配位置错误。如何正确分配6 站或任何站?

【问题讨论】:

  • 您的循环只执行一次迭代。它的目的是什么?不需要B=B。你期望它做什么?共有6个车站。正如您所写,“每个站点代表两列两行”,输出中不应该有 12 行和 12 列吗?你能解释一下你想要的输出与输入数据的关系吗?
  • 抱歉不清楚,感谢回复。忽略B=B,它只是让我看到矩阵。我会尽力解释最好的。矩阵B 的行代表它有 12 行的每个站点的总数 x,y。而该列仅代表不稳定站点的x,y,这就是为什么它有 6 个列。在示例中,第 3、4 行和第 1、第 2 列与第 2 站相关。第 5、第 5、第 6 行和第 3、第 4 列与第 3 站相关。第 11、第 12 行和第 5、第 6 列与第 6 站相关。这就是为什么我想将数字 1 移到第 5 列和第 6 列。
  • 您没有通过一次迭代来解释循环的目的。要查看矩阵,不需要B=B,只需要Bdisp(B); 在示例中,第3、4行和第1、2列与车站 2. 它们有什么关系?
  • 实际上我不知道迭代只是一次,因为我对编程真的很陌生。对于列和行,行是根据从 1 到 6 的站数排列的。列根据我的输入 uspt=[2 3 6]

标签: matlab matrix


【解决方案1】:

这里不需要循环。

m = stn*2;         %Number of rows of the required matrix
n = numel(uspt)*2; %Number of columns of the required matrix
B = zeros(m,n);    %Initializing B with all zeros

%finding row and column indices whose elements are to be changed
row = sort([uspt*2-1, uspt*2]);   %sorted row indices
col = 1:n;         %column indices

linInd = sub2ind([m,n], row,col); %Converting row and column subscripts to linear indices
B(linInd) = 1;     %Changing the values at these indices to 1

或作为两个班轮:

B = zeros(stn*2, numel(uspt)*2);
B(sub2ind([stn*2,numel(uspt)*2], sort([uspt*2-1, uspt*2]),1:numel(uspt)*2) = 1;    

【讨论】:

  • @TaufikIsmail 乐于提供帮助 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-27
  • 1970-01-01
  • 2014-01-30
  • 1970-01-01
  • 2017-05-09
  • 1970-01-01
  • 2021-11-02
相关资源
最近更新 更多