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

11 views (last 30 days)
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 Comment
Jonathan
Jonathan on 7 Feb 2019
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! :)

Sign in to comment.

Answers (1)

James Tursa
James Tursa on 9 Jul 2015
Edited: James Tursa on 9 Jul 2015
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.

Categories

Find more on Sparse Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!