vectorization - problem with zeros

2 次查看(过去 30 天)
I need to expand a small matrix A into a bigger one according to a pattern defined by a an array R. But the array may contain zeros so as to know that the rows and columns marked''0'' should be omitted. Here are the matrices:
A=[1 3 2 4; R=[1;
5 6 7 8; 3;
9 1 2 3; 0;
4 5 6 2]; 7];
R'=[1 3 0 7];
% ... the resulting matrix would be:
B=[1 0 3 0 0 0 4;
0 0 0 0 0 0 0;
5 0 6 0 0 0 8;
0 0 0 0 0 0 0;
0 0 0 0 0 0 0;
0 0 0 0 0 0 0;
4 0 5 0 0 0 2];
B=zeros(7,7); B(R,R')=A ......returns an error
  1 个评论
Luffy
Luffy 2012-6-23
I do not think you can write B(R,R') as Subscript indices must either be real positive integers or logicals.

请先登录,再进行评论。

采纳的回答

Julius
Julius 2012-6-23
  • Thank you Monkey, I really appreciate your help, but it seems that I've found a more effective solution:*
A=[1 3 2 4;
5 6 7 8;
9 1 2 3;
4 5 6 2];
R=[1 3 0 7];
B=zeros(7);
RNZ=R(R ~= 0);
d=find(R);
T=A(d,d');
B(RNZ,RNZ')=T

更多回答(1 个)

Luffy
Luffy 2012-6-23
A(find(R==0),:)=0; % on doing this u make a row of A=0 at which R=0 assuming there is only 1 zero in R as per you example otherwise add a for loop.
A = [1 3 2 4;
5 6 7 8;
0 0 0 0;
4 5 6 2];
A(:,find(R'==0))=0; % on doing this u make a column of A=0 at which R'=0 assuming there is only 1 zero in R
A = [1 3 0 4;
5 6 0 8;
0 0 0 0;
4 5 0 2];
B = zeros(7); % to create bigger matrix B,i took it as per your example as 7X7 matrix,
B = [ 0 0 0 0 0 0 0;
0 0 0 0 0 0 0;
0 0 0 0 0 0 0;
0 0 0 0 0 0 0;
0 0 0 0 0 0 0;
0 0 0 0 0 0 0;
0 0 0 0 0 0 0];
j = 1;
for i =1:2:length(B(1,:))
l = 1;
for k = 1:2:length(B(:,1))
B(i,k) = A(j,l);
l = l+1;
end
j = j+1;
end
B;
B = [ 1 0 3 0 0 0 4;
0 0 0 0 0 0 0;
5 0 6 0 0 0 8;
0 0 0 0 0 0 0;
0 0 0 0 0 0 0;
0 0 0 0 0 0 0;
4 0 5 0 0 0 2];
% this should give you answer you are looking for
% I am not generally good at following coding practices,if u do not understand any part feel free to comment

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by