Indexing and replacing value in a zero matrix based on a table

조회 수: 4 (최근 30일)
Sunny
Sunny 2018년 12월 19일
답변: Walter Roberson 2018년 12월 19일
Hello,
I am trying to input a value in a zeros matrix of size 11*10. This is based on a variable which has three columns (Number, ID, ANS) as shown below. Now I want to insert the value in ANS which is -1 in the zeros matrix at 10x5 (ID x Number) position (index). Any suggestion on how this can be done?
Number ID ANS
5 10 -1

채택된 답변

Walter Roberson
Walter Roberson 2018년 12월 19일
If your Number and ID and ANS are scalar then
YourMatrix(Number, ID) = ANS;
If they are vectors then there are multiple approaches, including:
YourMatrix( sub2ind(size(YourMatrix), Number(:), ID(:)) ) = ANS(:);
Or
YourMatrix = YourMatrix + accumarray( Number(:), ID(:), ANS(:), size(YourMatrix) );
and there are approaches using sparse.

추가 답변 (1개)

Arvind Sathyanarayanan
Arvind Sathyanarayanan 2018년 12월 19일
Is this what you're looking for?
ID = 10; Number = 5; Ans = -1;
tmat = zeros(11,10);
tmat(ID,Number)=Ans;

카테고리

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

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by