MATLAB: Could anybody help me how to solve the error in the following code

indexing all cell groups

code:
global q;
m=[10 20 30 40 50];
n=[60 70 80 90 100]
for t= 1:length(m)
for r= 1:length(n)
A=rand(m(t),n(r));
n_=ceil(n(r)/m(t))
C=repmat(diag(1:m(t)),1,n_ )
unused_rows=1:m;
t=1;
while ~isempty(unused_rows)
n_rows=ceil(sqrt(randi(numel(unused_rows))));
rows=unused_rows(randsample(length(unused_rows),n_rows));
[~,idx]=find(ismember(unused_rows,rows));
unused_rows(idx)=[];
[C,C_part]=cluster_rows2(A,C,rows);
CP{q}=C_part %indxing all cells/groups
q=q+1;
end
end
end
All_CP=[cat(1, CP{:})] %combine all cells/groups into one cell
------------------------------------------------------------------
function [C,C_part]=cluster_rows2(A,B,rows)
global q;
A_part=A(rows,:);
B_part=B(rows,:);
%sum along the the vertical axis to get indices for the non-0 columns
non_0=sum(B_part);
%Repeat the vector back to the same size as the partial matrix. It will be
%converted to a logical later on.
non_0=repmat(non_0,length(rows),1);
%create a copy of B, as that is the basis for C
C=B;
C_part=B_part;
%for all non-zero columns, replace the 0 positions with the values from A
C_part(non_0 & C_part==0)=A_part(non_0 & C_part==0)
%paste the edited partial matrix back
C(rows,:)=C_part;
CP{q}=C_part;
end

Best Answer

The old problem of global variables.
global q;
...
CP{q} = C_part;
Now it seems like your q is not a scalar. It is impossible to find the reason for this, because by declaring it as global, the value can be set from anywhere.
It is impossible to fix this code for you, because you did not show the part, where q is defined. I recommend to omit the global and use a standard variable:
q = 1;
If you need it in cluster_rows2(), provide it as input argument.
It looks strange that
CP{q}=C_part;
appears in the subfunction and the mainfunction also. Defining CP inside cluster_rows2() is meaningless, because this variable is not returned to the caller.