could anybody help me how to solve the error in the following code
1 次查看(过去 30 天)
显示 更早的评论
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
4 个评论
Stephen23
2018-1-19
"...how to solve the error in the following code"
Simple: do NOT use global variables.
采纳的回答
Jan
2018-1-18
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.
5 个评论
Jan
2018-1-19
What is the purpose of the square brackets in this code:
All_EP=[cat(1, EP{:})]
Where are the "E_part"s coming from? I do not find this in your code.
? [] concatenates the included elements to a matrix, but here you provide one element only. So omit the useless brackets:
All_EP = cat(1, EP{:});
Now you ask for "vertically concatenate all E_part with respect to t and r". I do not know what "respect to t and r" means here. But "cat(1, EP{:})" looks good for a vertical concatenation. What is the problem with this command?
更多回答(1 个)
Torsten
2018-1-18
Initialize q to a value (e.g. 1) at the beginning of your code.
Best wishes
Torsten
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!