How to quickly assign the values of a matrix using a given array?
조회 수: 2 (최근 30일)
이전 댓글 표시
Dear All,
I have an array A which contains two columns of integers. I want to build a matrix B in the following way.
For example,
A = [2 9; 1 5; 8 3]
The matrix B should be suilt as follows:
B = [0 1 0 0 0 0 0 0 -1 0; 1 0 0 0 -1 0 0 0 0 0; 0 0 -1 0 0 0 0 1 0 0]
How can I create matrix B for a goven A?
Thanks.
Benson
댓글 수: 0
채택된 답변
DGM
2021년 5월 23일
편집: DGM
2021년 5월 23일
Here is one way:
A = [2 9; 1 5; 8 3]
s = [size(A,1) 10]; % you're going to have to specify the output width
B = zeros(s);
B(sub2ind(s,(1:s(1)).',A(:,1))) = 1;
B(sub2ind(s,(1:s(1)).',A(:,2))) = -1;
B % show the result
댓글 수: 2
DGM
2021년 5월 24일
I really have no familiarity with handling sparse matrices or how to optimize for them. I'm sure someone else can though.
추가 답변 (1개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Downloads에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!