Could anyone help me to obtain new_C for the below mentioned code
4 次查看(过去 30 天)
显示 更早的评论
If
C=[0 0 41 0 0;
45 0 0 0 0;
0 43 0 0 0;
0 0 0 42 0;
0 0 0 0 44]
non_0= sum(C);
non_0=repmat(non_0,2,1);
A_part=[ 1 2 3 4 5;
11 12 13 14 15;
6 7 8 9 10;
21 22 23 24 25;
26 27 28 29 30]
new_C=C;
new_C(non_0 & C==0)=A_part(non_0 & C==0)
but i want to have new_C in
[ 0 0 41 4 0;
45 12 0 0 15;
6 43 0 0 10;
0 0 23 42 0;
26 27 0 0 44]
5 个评论
Geoff Hayes
2018-1-3
I'm sorry, I don't understand what is meant by In new C row 1 and row 4 are sharing with each other. What are they sharing? What is common between row 1 and 4?
回答(1 个)
Rik
2018-1-5
Let me help you out here, before everybody jumps out of the window.
You have already had some help about how to get a vector with randperm that should denote which rows are clustered ( here is one example I found). In this post I'm going to skip that step. If you have trouble putting that step back into this code, DON'T ASK A NEW QUESTION. Reply here instead.
function C=cluster_rows(A,B,rows)
%extract the parts of the matrices
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;
end
You can call this function like this:
A=[ 1 2 3 4 5;
11 12 13 14 15;
6 7 8 9 10;
21 22 23 24 25;
26 27 28 29 30];
B=[0 0 41 0 0;
45 0 0 0 0;
0 43 0 0 0;
0 0 0 42 0;
0 0 0 0 44];
C_after_step_1=cluster_rows(A,B,[1 4]);
C=cluster_rows(A,C_after_step_1,[2 3 5]);
And, no, there isn't an easy way to do this without calling the function twice or repeating the code.
2 个评论
jaah navi
2018-1-5
Thanks.could you please help me if the size of the matrix A and B are (n,m) then how it can be done.
Rik
2018-1-5
编辑:Rik
2018-1-5
The function works on matrices of arbitrary sizes. As long as you provide row indices that are still inside the matrix dimensions, this will work. (so don't try to get row 1001 if your A and B have only 1000 rows)
The function processes the entire row at once, so the number of columns doesn't matter.
I would also be interested to know if you ( Jaah Navi and Prabha Kumaresan) are indeed working together on the same project.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Number Theory 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!