Sub values into multiple rows and columns simutaneously

I have a 10x10 matrix. I want to sub a few values into the matrix simultaneously, with the other values being zero. It would be time-consuming to sub the values one by one. Is there any way to do this?
For example, A=[zeros(10,10)] A(1,1)=-4 A(2,2)=-4 A(3,3)=-4
Is there a way to sub -4 into these locations at once?

댓글 수: 1

Does "to sub" mean "subtract" or "substitute"? According to your code "substitute" is meant.

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

 채택된 답변

Jan
Jan 2018년 1월 19일
Replacing 3 elements is not time consuming and the show code is very efficient. If run time is critical, you are working on another problem, obviously. Then it is better to explain the real problem, and not a very simplified version of it, which omits the actual time consuming details.
If you want to replace some thousands of elements, whose indices are store in two vectors:
x = [1,2,3]; % Can be much longer
y = [1,2,3];
index = sub2ind(size(A), x, y);
A(index) = -4;

추가 답변 (2개)

Walter Roberson
Walter Roberson 2018년 1월 19일

0 개 추천

Use sub2ind convert the row column pairs into linear indexing. Then index the left side with the linear indexes.
Jos (10584)
Jos (10584) 2018년 1월 19일
The words " a few" and " others remaining zero" might indicate that you also could use SPARSE matrices. For instance:
A = sparse([1 2 3],[1 2 3],-4,10,10)
full(A)

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2018년 1월 19일

답변:

2018년 1월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by