首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用逐行/列替换矩阵上的元素

用逐行/列替换矩阵上的元素
EN

Stack Overflow用户
提问于 2017-06-23 19:53:58
回答 1查看 66关注 0票数 0

我有6站,来自它的3不稳定。uspt是不稳定的,2, 3, 6说。

每个站代表两列,两行,例如,站1对应行1和2,站2对应行3和4等等。前两列对应于第一不稳定站,即站2;后两列(列3和4)对应下一不稳定站,即站3等等。

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

代码语言:javascript
复制
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]

以下是我尝试过的:

代码语言:javascript
复制
%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

我得到的是:

代码语言:javascript
复制
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站或任何车站的正确作业?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-06-23 21:12:41

这里不需要循环。

代码语言:javascript
复制
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

或者两个班轮:

代码语言:javascript
复制
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;    
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44729037

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档