loopsmatlabmatrixdimension

Dimension matrix error in while loop Matlab


I want my code to give me a final matrix of 31x5

nplants=5
nhours=24

for j =nplants:-1:1
    for comb = fliplr(nchoosek(1:nplants, j).') 
        outage = ones(nhours, nplants); 
        outage(:, comb) = 0; % make columns zero

       prodout = outage.*prodordered;
        meritorder = prodout(:,1);
        for i=2:nplants,
        meritorder(:,i) = meritorder(:,i-1) + prodout(:,i);
        end
    active = zeros(nhours,nplants);
    active(:,1) = ones(nhours,1);
    
    for i=1:nhours,
        k = 1;
        while meritorder(i,k) <= hourlydata.demand(i)
                k = k+1;
            active(i,k) = 1;
        end
    end 
    supply = active.*prodout;
    varcost1 = active.*outage.*cncordered;
    totsupout = sum(supply,2);
    priceout = max(varcost1')';
    
    hourlyprofit1=(repmat(priceout,1,5)-varcost1).*prodout;
    profit1(:,j) = sum(hourlyprofit1);

    end
    
end

Where prodordered is a 24x5 matrix, hourlydata.demand is 24x1, and cncordered is 24x5.

I want profit1 to store the results, becoming a 31x5 matrix.

When I try running this code, I get:

Index in position 2 exceeds array bounds. Index must not exceed 5.
        while meritorder(i,k) <= hourlydata.demand(i)

I don't understand my dimension matrix mistake in the while loop.


Solution

  • you're "trying" to look for a condition in the while line you've got to k=6. the condition that is tested is if meritorder(i,6) <= hourlydata.demand(i) . but meritorder is an array 24x5 so you cant access that col because it doesn't exist. so the whole condition is problematic to while. Think of that as an if x>1 condition where you haven't defined what x is.

    You can solve it by replacing the while with a for loop (for k=1:5) following an if condition if meritorder(i,k) <= hourlydata.demand(i); active(i,k) = 1; end