开发者

Replace elements in a matrix according to the coordinates in matlab

I am curious about what is the best way to do this: assume I have a 10x10 zero matrix and I want to replace the zeros with ones with the known coordinates, in the beginning I am thing about write a for loop to replace the elements one by one by reading out the x and y. Is there any other easier way to do it?

Example:

mat=zeros(10);
x=[1,3,5,7,9]'; 
y=[2,4,6,8,10]';
newmat= 开发者_StackOverflow[0 0 0 0 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 1 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 0 0 0 0 0 0 0 0 0 
         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 1 0]  


For this kind of manipulations use sub2ind, like

> mat=zeros(10); x=[1,3,5,7,9]'; y=[2,4,6,8,10]';
> mat(sub2ind([10 10], y, x))= 1
mat =
   0   0   0   0   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   1   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   0   0   0   0   0   0   0   0   0
   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   1   0

Update: To contrast this with innocent looking assigmnet mat(y, x)= 1.

> mat= zeros(10);
> mat(y, x)= 1
mat =
   0   0   0   0   0   0   0   0   0   0
   1   0   1   0   1   0   1   0   1   0
   0   0   0   0   0   0   0   0   0   0
   1   0   1   0   1   0   1   0   1   0
   0   0   0   0   0   0   0   0   0   0
   1   0   1   0   1   0   1   0   1   0
   0   0   0   0   0   0   0   0   0   0
   1   0   1   0   1   0   1   0   1   0
   0   0   0   0   0   0   0   0   0   0
   1   0   1   0   1   0   1   0   1   0


You can do what you want by indexing the specific rows and columns into the matrix and assigning values to the diagonal.

mat(y,x)=eye(length(x))
mat =

     0     0     0     0     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     1     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     0     0     0     0     0     0     0     0     0
     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     1     0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜