Why am I receiving this error when trying to implement sparse?

조회 수: 7 (최근 30일)
Ellie
Ellie 2015년 7월 9일
댓글: Walter Roberson 2019년 2월 7일
I am trying to modify this code from file exchange. It works perfectly, but it won't allow me to use data that includes zeros. I cannot figure out why or how to modify it so it will allow for zeros and the code is useless unless it can do this.
Here is the error: Error using sparse, Index into matrix must be positive.
And here is the partially modified code.
markovChain = [2 3 3 3 0 4 3 2 4 0 2 1 4];
Norder = 2;
Nstates = max(markovChain);
if Norder == 1,
%get transition matrix
transitionMatrix = full(sparse(markovChain(1:end-1),markovChain(2:end),1,Nstates^Norder,Nstates^Norder));
else
%get Norder-contiguous sequences of the markov chain
ngrams = [];
for i = 0:Norder-1
ngrams = [ngrams, circshift(markovChain,[0 -1*(i)])'];
end
ngrams = cellstr(num2str( ngrams));
ngrams = ngrams(1:end-Norder);
%create all combinations of Norder-contiguous sequences
[x{1:Norder}] = ndgrid(1:Nstates);
%format x to cell
evalStr = ('xCell = cellstr(num2str([');
for i = 1:Norder
evalStr = [evalStr 'x{' num2str(i) '}(:) '];
end
evalStr = [evalStr ']));'];
eval(evalStr);
%map ngrams to numbers
[gn,~,g]=unique([xCell;ngrams]);
s1 = g(Nstates^Norder+1:end);
%states following the ngrams
s2 = markovChain(Norder+1:end);
%reordered xCell.
columnStates = gn(1:Nstates^Norder);
%get transition matrix
transitionMatrix = full(sparse(s1,s2,1,Nstates^Norder,Nstates^Norder));
end
transitionMatrix
%plot the transition matrix
imagesc(transitionMatrix);
str= 'Transition Matrix of the Markov Chain:\n';
str=[str sprintf('%d',markovChain) '...'];
title(sprintf(str));
%replace tickLabels with states.
set(gca,'YTick',1:numel(columnStates));
set(gca,'YTickLabel',columnStates);
set(gca,'XTick',1:Nstates);
set(gca,'XTickLabel',1:Nstates);
  댓글 수: 1
Jonathan
Jonathan 2019년 2월 7일
Another reason for "Error using sparse, Index into matrix must be integer" is if there are NaNs in the vector. I just found that out with a binary search on a very long vector! :)

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

답변 (1개)

James Tursa
James Tursa 2015년 7월 9일
편집: James Tursa 2015년 7월 9일
The variable markovChain (or s1 or s2) has 0's in it, and you are attempting to use this for indexes when building the sparse matrix. MATLAB does not allow 0 indexes, hence the error message you are getting.
You will have to reformulate your program to avoid using 0 indexes.

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by