index exceeding matrix dimentions - matlab

I was trying to get this low order recursive function in matlab. i want to calculate the probability of status of a site at next time step, given that I have the initial probability of that being a status.
P= Probability
x= status(0,1)
Dij= probability to pick a site
P(Status of Site(i) being x at next time step)= Summation[P(Status of Site(i) being x at previous time step)*Dij]
and this is what I have done! but my index always exceeds matrix dimensions! I need help with this.
clear all;
clc;
%function [t,i]= CopyingInfluenceModel
%%Define constants
%% generate some random weights vectori.e. the transition matrix=C
% C=[0 (1,2) 0 (1,4) 0 0 0;
% (2,1) 0 (2,3) 0 0 0 0;
% 0 (3,2) 0 (3,4) 0 0 0;
% (1,4) 0 (4,3) 0 (4,5) 0 0;
% 0 0 0 (5,4) 0 (5,6) (5,7);
% 0 0 0 0 (6,5) 0 (6,7);
% 0 0 0 0 (7,5) (7,6) 0];
%copying probabilities=branch weights
onetwo=0.47;
twothree=0.47;
threefour=0.47;
onefour=0.47;
fourfive=0.023;
fivesix=0.47;
fiveseven=0.47;
sixseven=0.47;
selfweight1=0.06;
selfweight2=0.037;
% SourceNodes - a list of Nodes that are forced to be kept in one side of the cut.
% WeightedGraph - symetric matrix of edge weights. Wi,j is the edge
% connecting Nodes i,j use Wi,j=0 or Wi,j == inf to indicate unconnected Nodes
WeightedGraph=[0 onetwo 0 onefour 0 0 0;
onetwo 0 twothree 0 0 0 0;
0 twothree 0 threefour 0 0 0;
onefour 0 threefour 0 fourfive 0 0;
0 0 0 fourfive 0 fivesix fiveseven;
0 0 0 0 fivesix 0 sixseven;
0 0 0 0 fiveseven sixseven 0];
Dij=sparse(WeightedGraph);
% Initializing the variables
t=[];
i=[];
%assigining the initial conditions
t(1)=0;
p(1)= 0.003; %% initial probability of status
%set index no i to 1(initial condition for i=1)
i=1;
%repeating calculating new probabilities
%% If the probability is zero, terminate while loop
while p(i)>=0
%calculate at the next time step for given index no
t(i+1)= t(i);
%calculate the status_probability at given time t=(i+1)
[p(i+1)]=[p(i)]+sum([p(i)]*[Dij(i)]);
[NextStatus(i)]= [p(i+1)]
%index i increases by 1 to calculate next probability
i=i+1;
end
Stack Trace is:
%%??? Index exceeds matrix dimensions.
%%Error in ==> CopyingInfluenceModel at 54
%%[p(i+1)]=[p(i)]+sum([p(i)]*[Dij(i)]);

The problem is Dij not p. Dij has a fixed length so when i exceeds that the program throws an error.
Added:
I can't really see your logic in the code, but I have a strong feeling that you are calculating something wrong. Dij is a 7 x 7 matrix but you treat it as a vector by calling Dij(i). If you are trying to multiply something by a row or column, you need the Dij(i,:) or Dij(:, i) notation.

The logic as you posted it doesn't work, essentially, p(i+i) isn't defined yet. There are a few ways to do it, depending on if you want to keep p or not. I'll post a method that keeps p around, but some work could be done to make the code more efficient.
p=[p;p(i)+sum(p(i)*Dij(i))];
NextStatus(i)= p(i+1)

Related

Replace repeated value based on sequence size - Matlab

I have a 2D matrix composed of ones and zeros.
mat = [0 0 0 0 1 1 1 0 0
1 1 1 1 1 0 0 1 0
0 0 1 0 1 1 0 0 1];
I need to find all consecutive repetitions of ones in each row and replace all ones with zeros only when the sequence size is smaller than 5 (5 consecutive ones):
mat = [0 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0];
Any suggestion on how to approach this problem would be very welcome.
You can use diff to find the start and end points of the runs of 1, and some logic based on that to zero out the runs which are too short. Please see the below code with associated comments
% Input matrix of 0s and 1s
mat = [0 0 0 0 1 1 1 0 0
1 1 1 1 1 0 0 1 0
0 0 1 0 1 1 0 0 1];
% Minimum run length of 1s to keep
N = 5;
% Get the start and end points of the runs of 1. Add in values from the
% original matrix to ensure that start and end points are always paired
d = [mat(:,1),diff(mat,1,2),-mat(:,end)];
% Find those start and end points. Use the transpose during the find to
% flip rows/cols and search row-wise relative to input matrix.
[cs,r] = find(d.'>0.5); % Start points
[ce,~] = find(d.'<-0.5); % End points
c = [cs, ce]; % Column number array for start/end
idx = diff(c,1,2) < N; % From column number, check run length vs N
% Loop over the runs which didn't satisfy the threshold and zero them
for ii = find(idx.')
mat(r(ii),c(ii,1):c(ii,2)-1) = 0;
end
If you want to throw legibility out of the window, this can be condensed for a slightly faster and denser version, based on the exact same logic:
[c,r] = find([mat(:,1),diff(mat,1,2),-mat(:,end)].'); % find run start/end points
for ii = 1:2:numel(c) % Loop over runs
if c(ii+1)-c(ii) < N % Check if run exceeds threshold length
mat(r(ii),c(ii):c(ii+1)-1) = 0; % Zero the run if not
end
end
The vectorized solution by #Wolfie is nice and concise, but a bit hard to understand and far from the wording of the problem. Here is a direct translation of the problem using loops. It has the advantage of being easier to understand and is slightly faster with less memory allocations, which means it will work for huge inputs.
[m,n] = size(mat);
for i = 1:m
j = 1;
while j <= n
seqSum = 1;
if mat(i,j) == 1
for k = j+1:n
if mat(i,k) == 1
seqSum = seqSum + 1;
else
break
end
end
if seqSum < 5
mat(i,j:j+seqSum-1) = 0;
end
end
j = j + seqSum;
end
end

How does Y = eye(K)(y, :); replace a "for" loop? Coursera

Working on an assignment from Coursera Machine Learning. I'm curious how this works... From an example, this much simpler code:
% K is the number of classes.
K = num_labels;
Y = eye(K)(y, :);
seems to be a substitute for the following:
I = eye(num_labels);
Y = zeros(m, num_labels);
for i=1:m
Y(i, :)= I(y(i), :);
end
and I have no idea how. I'm having some difficulty Googling this info as well.
Thanks!
Your variable y in this case must be an m-element vector containing integers in the range of 1 to num_labels. The goal of the code is to create a matrix Y that is m-by-num_labels where each row k will contain all zeros except for a 1 in column y(k).
A way to generate Y is to first create an identity matrix using the function eye. This is a square matrix of all zeroes except for ones along the main diagonal. Row k of the identity matrix will therefore have one non-zero element in column k. We can therefore build matrix Y out of rows indexed from the identity matrix, using y as the row index. We could do this with a for loop (as in your second code sample), but that's not as simple and efficient as using a single indexing operation (as in your first code sample).
Let's look at an example (in MATLAB):
>> num_labels = 5;
>> y = [2 3 3 1 5 4 4 4]; % The columns where the ones will be for each row
>> I = eye(num_labels)
I =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
>> Y = I(y, :)
Y =
% 1 in column ...
0 1 0 0 0 % 2
0 0 1 0 0 % 3
0 0 1 0 0 % 3
1 0 0 0 0 % 1
0 0 0 0 1 % 5
0 0 0 1 0 % 4
0 0 0 1 0 % 4
0 0 0 1 0 % 4
NOTE: Octave allows you to index function return arguments without first placing them in a variable, but MATLAB does not (at least, not very easily). Therefore, the syntax:
Y = eye(num_labels)(y, :);
only works in Octave. In MATLAB, you have to do it as in my example above, or use one of the other options here.
The first set of code is Octave, which has some additional indexing functionality that MATLAB does not have. The second set of code is how the operation would be performed in MATLAB.
In both cases Y is a matrix generated by re-arranging the rows of an identity matrix. In both cases it may also be posible to calculate Y = T*y for a suitable linear transformation matrix T.
(The above assumes that y is a vector of integers that are being used as an indexing variables for the rows. If that's not the case then the code most likely throws an error.)

How to count the number of 1's from the total matrix

I have code like below:
N=10;
R=[1 1 1 1 1 0 0 0 0 0;1 1 1 1 1 1 1 1 1 1];
p=[0.1,0.2,0.01];
B = zeros(N , N);
B(1:N,1:N) = eye(N);
C=[B;R];
for q=p(1:length(p))
Rp=C;
for i=1:N
if(rand < p)
Rp(i,:) = 0;
end
end
end
from this code I vary the value of p. So for different value of p, i am getting different Rp. Now I want to get the total number of "1"'s from each Rp matrix. it means may be for p1 I am getting Rp1=5, for p2, Rp=4.
For example
Rp1=[1 0 0 0 0;0 1 0 0 0;0 0 0 0 0],
Rp2=[1 0 0 0 0;0 1 0 0 0;1 0 0 0 0],
Rp3=[0 0 0 0 0;0 1 0 0 0;0 0 0 0 0],
So total result will be 2,3,1.
I want to get this result.
If the matrix contains only 0 and 1 you are trying to count the nonzero values and there is a function for that called nnz
n = nnz(Rp);
As I mentioned in the comments you should replace
if(rand < p)
with
if(rand < q)
Then you can add the number of nonzero values to a vector like
r = [];
for q=p(1:length(p))
Rp=C;
for i=1:N
if(rand < p)
Rp(i,:) = 0;
end
end
r = [r nnz(Rp)];
end
Then r will contain your desired result. There are many ways to improve your code as mentioned in other answers and comments.
Assuming Rp is your matrix, then simply do one of the following:
If your matrix only contains zeros and ones
sum(Rp(:))
Or if your matrix contains multiple values:
sum(Rp(:)==1)
Note that for two dimensional matrices sum(Rp(:)) is the same as sum(sum(Rp))
I think your real question is how to save this result, you can do this by assigning it to an indexed varable, for example:
S(count) = sum(Rp(:));
This will require you to add a count variable that increases with one every step of the loop. It will be good practice (and efficient) to initialize your variable properly before the loop:
S = zeros(length(p),1);
If you need to count the 1's in any matrix M you should be able to do sum(M(:)==1)

Time series in Finite State Space Markov chain

I have state transition probability matrix for state K=8,
trans =
0.9245 0.0755 0 0 0 0 0 0
0.0176 0.9399 0.0425 0 0 0 0 0
0 0.0290 0.9263 0.0447 0 0 0 0
0 0 0.0465 0.9228 0.0307 0 0 0
0 0 0 0.0731 0.8979 0.0290 0 0
0 0 0 0 0.0907 0.8857 0.0236 0
0 0 0 0 0 0.1080 0.8750 0.0170
0 0 0 0 0 0 0.1250 0.8750
I need to generate time vector/time series from the transition matrix using Matlab. Can anyone suggest me on how to generate the time series from this state transition probability matrix in Matlab.
If by generate you mean sample from the transition matrix this should work:
function [chain,state] = simulate_markov(x,P,pi0,T);
%% x = the quantity corresponding to each state, typical element x(i)
%% P = Markov transition matrix, typical element p(i,j) i,j=1,...n
%% pi0 = probability distribution over initial state
%% T = number of periods to simulate
%%
%% chain = sequence of realizations from the simulation
%% Modification of progam by L&S.
n = length(x); %% what is the size of the state vector?
E = rand(T,1); %% T-vector of draws from independent uniform [0,1]
cumsumP = P*triu(ones(size(P)));
%% creates a matrix whose rows are the cumulative sums of
%% the rows of P
%%%%% SET INITIAL STATE USING pi0
E0 = rand(1,1);
ppi0 = [0,cumsum(pi0)];
s0 = ((E0<=ppi0(2:n+1)).*(E0>ppi0(1:n)))';
s = s0;
%%%%% ITERATE ON THE CHAIN
for t=1:T,
state(:,t) = s;
ppi = [0,s'*cumsumP];
s = ((E(t)<=ppi(2:n+1)).*(E(t)>ppi(1:n)))';
end
chain = x'*state;
Source : http://www-scf.usc.edu/~ngarnold/Markov%20Chains%20Notes.pdf

Matlab+ Graph theory+ specific weight assignment

I want to assign weights to the edges such that the Sum of (the weights coming to a node) and its own weight add to one.
here is what I tried:
clear all;
close all;
clc;
%% building the graph
g=graph;
for k=1:6
add(g,k,k+1)
add(g,1,4)
add(g,5,7)
end
%%assigining the statuses 0 and 1
%label(g,1,'0');
%label(g,2,'1');
%label(g,3,'1');
%label(g,4,'1');
%label(g,5,'1');
%label(g,6,'0');
%label(g,7,'0');
figure,ldraw(g);
%x=rand(1,1);
%y=rand(1,1)
%% get line info from the figure
lineH = findobj(gca, 'type', 'line');
xData = cell2mat(get(lineH, 'xdata')); % get x-data
yData = cell2mat(get(lineH, 'ydata')); % get y-data
%% if an edge is between (x1,y1)<->(x2,y2), place a label at
%%the center of the line, i.e. (x1+x2)/2 (y1+y2)/2 etc
labelposx=mean(xData');
labelposy=mean(yData');
%% generate some random weights vectori.e. the probability matrix
weights=rand(1,1,length(labelposx))
% plot the weights on top of the figure
text(labelposx,labelposy,mat2cell(weights), 'HorizontalAlignment','center',...
'BackgroundColor',[.7 .9 .7]);
%%Transition matrix or markov matrix
% Transition=[0 (1,2) 0 (1,4) 0 0 0;
% (2,1) 0 (2,3) 0 0 0 0;
% 0 (3,2) 0 (3,4) 0 0 0;
% 0 0 (4,3) 0 (4,5) 0 0;
% 0 0 0 (5,4) 0 (5,6) (5,7);
% 0 0 0 0 (6,5) 0 (6,7);
% 0 0 0 0 (7,5) (7,6) 0];
Transition= [0 weights(:,:,8) 0 weights(:,:,6) 0 0 0;
weights(:,:,8) 0 weights(:,:,7) 0 0 0 0;
0 weights(:,:,7) 0 weights(:,:,5) 0 0 0;
weights(:,:,6) 0 weights(:,:,5) 0 weights(:,:,4) 0 0;
0 0 0 weights(:,:,4) 0 weights(:,:,3) weights(:,:,2);
0 0 0 0 weights(:,:,3) 0 weights(:,:,1);
0 0 0 0 weights(:,:,2) weights(:,:,1) 0]
%set_matrix
%%dij-- Probability matrix
sparse(Transition);
d=[weights(:,:,8);weights(:,:,7);weights(:,:,5);weights(:,:,4);
weights(:,:,3);weights(:,:,1);weights(:,:,1)]
%%Si[k]-- matrix of the statuses(labels)
%S=[0 1 1 1 1 0 0]
For eg: The addition of weights coming to node four, plus its own weight should be equal to 1
Check out this nice random vectors generator with fixed sum FEX file. I think this will answer your question.
see also more on this SO link Non biased return a list of n random positive numbers (>=0) so that their sum == total_sum