MATLAB: I need to solve this error: Attempted to access CC(:,2); index out of bounds because size(CC)=[9,1].

Hi, I'm starter in Matlab. I have a problem with the error:Attempted to access CC(:,2); index out of bounds because size(CC)=[9,1]. here is the script:
data=load('squat');
ALeft1=data.ALeft1;
AA=zeros(size(ALeft1)); BB=zeros(size(ALeft1)); CC=zeros(size(ALeft1));
delta1=12;
t1=1;
EnergyAveScenario=zeros(length(ALeft1),length(delta1));
for a=t1:1:delta1
EnergyAveScenario(:,a)=f_ET(ALeft1,[80;120],[35;50;60],a);
end
a=zeros(size(EnergyAveScenario(1,:)));
c=zeros(size(EnergyAveScenario(1,:)));
b=zeros(size(EnergyAveScenario(1,:)));
for j=t1:1:delta1
for i=1:1:numel(EnergyAveScenario(:,j))
if EnergyAveScenario(i,j)<=80
AA(i,j)=EnergyAveScenario(i,j);
elseif EnergyAveScenario(i,j)>80 && EnergyAveScenario(i,j)<=120
BB(i,j)=EnergyAveScenario(i,j);
else
CC(i,j)=EnergyAveScenario(i,j);
end
end
end
for j=t1:1:delta1
a(:,j)=numel(find(AA(:,j)~=0));
c(:,j)= numel(find(CC(:,j)~=0));
b(:,j)= numel(find(BB(:,j)~=0));

Best Answer

The error message is pretty clear in what the problem is - the code is trying to access the second column of CC when there is only the one column. Presumably this is occurring at the following line
c(:,j)= numel(find(CC(:,j)~=0));
What is kind of interesting is why a similar error isn't being thrown on the previous line
a(:,j)=numel(find(AA(:,j)~=0));
since AA, BB, and CC have all been sized identically at
AA=zeros(size(ALeft1)); BB=zeros(size(ALeft1)); CC=zeros(size(ALeft1));
In your first for loop, the code iterates over j and within the inner for loop, these three matrices are being updated with the dimensions of AA and BB changing from what they originally were. Is this intentional? The outer loop j is iterating over the columns of EnergyAveScenario and the inner loop i is iterating over the number of rows in EnergyAveScenario where this matrix has been sized as
EnergyAveScenario=zeros(length(ALeft1),length(delta1));
Note that the above sizing seems incorrect. Since delta1 is a scalar (12) then the length(delta1) returns just one. The above assignment should probably be
EnergyAveScenario=zeros(length(ALeft1),delta1);
especially as the subsequent for loop grows EnergyAveScenario along its columns.
I think that there is an assumption that all four matrices (AA,*BB*,*CC*,*EnergyAveScenario*) should be sized identically. If that is the case, then do so
lenALeft1 = length(ALeft1);
AA = zeros(lenALeft1,delta1);
BB = zeros(lenALeft1,delta1);
CC = zeros(lenALeft1,delta1);
EnergyAveScenario = zeros(lenALeft1,delta1);
Does the above make sense?