필터 지우기
필터 지우기

Sparse Arrays - Specific Function?

조회 수: 1 (최근 30일)
Maroulator
Maroulator 2014년 11월 30일
편집: Mohammad Abouali 2014년 11월 30일
I need to initialize a 100X100 sparse array with random values and a density of 5%; I then need to set all diagonal elements of that sparse array to 1. I can get the first piece of my problem using the sprand(100,100,0.05) command, but I have no idea how to do the second piece without using speye(100) which will overwrite the random values of my initial matrix.
Other than using a for loop, does anyone know of a function that will just set all diagonal elements of my 100X100 matrix to 1 without losing the random values ascribed to some of the off-diagonal elements?
Thanks in advance.

채택된 답변

Mohammad Abouali
Mohammad Abouali 2014년 11월 30일
편집: Mohammad Abouali 2014년 11월 30일
s=sprand(100,100,0.05);
s(sub2ind(size(s),1:100,1:100))=1.0;
or
s=sprand(100,100,0.05);
s(1:101:(100*100))=1.0;

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by