Assignment and accessing using indices

조회 수: 9 (최근 30일)
Jeff Wood
Jeff Wood 2016년 6월 5일
댓글: Jeff Wood 2016년 6월 6일
I had a question about how to do a particular type of assignment using indices. The code below is a simplified example.
k = zeros(4,4);
v = [2,3];
k(v,v) = 1;
My intention was to get a result that looks like
ans =
[0, 0, 0, 0;
0, 1, 0, 0;
0, 0, 1, 0;
0, 0, 0, 0]
But unfortunately the result is:
ans =
[0, 0, 0, 0;
0, 1, 1, 0;
0, 1, 1, 0;
0, 0, 0, 0]
So my question is: Is there a way to access individual elements (rather than rectangular regions) without using a for loop (Which I understand is computationally expensive in MatLab)?

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2016년 6월 5일
k = zeros(4,4);
v = [2,3];
idx=sub2ind(size(k),v,v)
k(idx) = 1;
  댓글 수: 1
Jeff Wood
Jeff Wood 2016년 6월 6일
Thanks,
I should have mentioned that v might be different for rows and columns (i.e. I was using the generic case where they were the same).

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

John BG
John BG 2016년 6월 6일

Chad Greene
Chad Greene 2016년 6월 5일
Try this:
A = zeros(4);
lin = sub2ind([4 4],2:3,2:3);
A(lin) = 1;

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by