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

6 次查看(过去 30 天)
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 中查找有关 Resizing and Reshaping Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by