Error using sparse Index into matrix must be positive.

6 ビュー (過去 30 日間)
fadams18
fadams18 2020 年 2 月 21 日
編集済み: Fabio Freschi 2020 年 2 月 21 日
Im converting a code from python to Matlab
% Python Code
% ksq and old_dim are dimensions e.g. 5, or 10
C = np.arange(old_dim)
R = np.random.random_integers(ksq, size=old_dim) - 1
D = np.random.randint(2, size=old_dim) * 2 - 1
S = scipy.sparse.csr_matrix((D, (R, C)), shape=(ksq, old_dim))
The Matlab code i wrote.
C=1:old_dim;
R = randi(ksq,[1,old_dim]) - 1;
D = randi(2, [1,old_dim]) * 2 - 1;
S = sparse(R,C,D,ksq,old_dim);
When i run my matlab code, it tells me
Error using sparse Index into matrix must be positive.
My guess is when i have a zero in one of the variables R C D thats when it throws this error? and what could be a solution to this. thanks
  1 件のコメント
Adam
Adam 2020 年 2 月 21 日
Matlab indexes from 1 so just add one to any indexing you have in a 0-indexed language.

サインインしてコメントする。

回答 (1 件)

Fabio Freschi
Fabio Freschi 2020 年 2 月 21 日
編集済み: Fabio Freschi 2020 年 2 月 21 日
Simply remove "-1" from the definition of R. randi returns pseudorandom integers between 1 and the first inupt. The entries of C will never be 0.
C = 1:old_dim;
R = randi(ksq,[1,old_dim]);
D = randi(2, [1,old_dim]) * 2 - 1;
S = sparse(R,C,D,ksq,old_dim);

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by