MATLAB: Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.

for loop

I am trying to run a simple for loop to create a matrix that made up of 2n vectors of random numbers that all sum to 1. I have the proper code for making a singular vector, but am having issues with my for loop. The resulting matrix should be of size 2nx2n the loop is 2n long and the vectors are 2n long, so I don't understand why the sides are mismatched.
r = rand(1,2.*n); %2n random numbers that will make up the vectors in P
r = r/sum(r); %normalize the vector to 1
thesum = sum(r); %check that the vector sums to 1
for i = 1:2.*n
P(i) = r./sum(r); %repeat random vectors 2.*n times to create the matrix of probabilities

Best Answer

  • Try this:
    n = 5;
    P = zeros(2 * n, 2 * n);
    for row = 1 : 2 * n
    thisRow = rand(1, 2.*n); % 2n random numbers that will make up the rows of P
    thisRow = thisRow / sum(thisRow); % Normalize the sum of the row vector to 1
    % Assign this row to P
    P(row, :) = thisRow; % Stuff this row into P
    P % Report to command window.
    % Check that all rows sum to 1
    rowSums = sum(P, 2) % Sum each row, going across columns