用行/列替换矩阵的行/列

时间:2017-06-23 19:53:58

标签: matlab matrix

我有https://drive.google.com/drive/folders/0BzbdjY-H_HzZTC1Rci1nY0F4VFU?usp=sharing 个电台,6电台不稳定。不稳定的电台3uspt

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

我想创建一个矩阵2, 3, 6,使用上述信息为不稳定点指定数字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] 2电台获得了正确的分配,而3电台的分配位置错误。如何为6电台或任何电台完成正确的分配?

1 个答案:

答案 0 :(得分: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;