Replacing elements on matrix with row/column by row/column
我有
每个站点代表两列和两行,例如站点 1 对应于第 1 行和第 2 行,站点 2 对应于第 3 和 4 行,以此类推。前两列对应于第一个不稳定站点,即站点 2。接下来的两列(第 3 列和第 4 列)对应于下一个不稳定站点,即站点 3,依此类推。
我想创建一个矩阵
1 2 3 4 5 6 7 8 9 10 11 12 | 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] |
这是我尝试过的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | %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 |
我得到了什么:
1 2 3 4 5 6 7 8 9 10 11 12 | 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] |
这里不需要循环。
1 2 3 4 5 6 7 8 9 10 | 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 |
或作为两个班轮:
1 2 |