Vector decomposition with Matlab

조회 수: 9 (최근 30일)
Gogu
Gogu 2019년 7월 11일
편집: Bruno Luong 2019년 7월 12일
Hello !
I want to split a vector b, in two parts, b1 and b2, like that:
b= [2; 1; 2; 1; 0; 1; 2; 1; 2]
b1=[2; 1; 1; 1; 0; 0; 1; 0; 0]
b2=[0; 0; 1; 0; 0; 1; 1; 1; 2]
But my code, work only for n=4; for n>4, don't work fine.
n=4;
b=zeros((n-1)^2,1);
b(1)=2;
b(2:(n-2))=ones(n-3,1);
b(n-1)=2;
for i=1:n-3
b((n-1)*i+1)=1;
b((n-1)*(i+1))=1;
end
b((n-1)*(n-2)+1)=2;
b((n-1)*(n-2)+2:(n-1)*(n-2)+n-2)=ones(n-3,1);
b((n-1)^2)=2;
b1(1)=2;
b1(2:(n-2))=1;
b1(n-1)=1;
for i=1:n-3
b1((n-1)*i+1)=1;
b1((n-1)*(i+1))=0;
end
b1((n-1)*(n-2)+1)=1;
b1(n*2:(n-1)*(n-2))=0;
b1((n-1)*(n-2)+2:(n-1)*(n-2)+n-2)=zeros(n-3,1);
b1((n-1)^2)=0;
b2(1)=0;
b2(2:(n-2))=0;
b2(n-1)=1;
b2((n-1)*(n-2))=1;
b2((n-1)*(n-2)+1)=1;
b2((n-1)*(n-2)+2:(n-1)*(n-2)+n-2)=ones(n-3,1);
b2((n-1)^2)=2;
  댓글 수: 2
Torsten
Torsten 2019년 7월 11일
One can split a vector in two vectors in many ways. What are the rules ?
Gogu
Gogu 2019년 7월 11일
b=b1+b2
For the first half of elements, the rules are:
the first 2 keep in b1; 1 keep in b1; 2 split in two values of 1; 1 keep in b1
For the second half of elements, the rules are:
1 move to b2; 2 split in two; the last 2, move to b2

댓글을 달려면 로그인하십시오.

채택된 답변

Bruno Luong
Bruno Luong 2019년 7월 11일
편집: Bruno Luong 2019년 7월 12일
b= [2; 1; 2; 1; 0; 1; 2; 1; 2]
b1=min(b,1);
b1([find(b==2,1,'first'),find(b==2,1,'last')])=2;
b2=b-b1;
n=length(b);
tail=floor(n/2)+1:n; %or ceil?
[b1(tail),b2(tail)]=deal(b2(tail),b1(tail));
b1
b2
  댓글 수: 2
Gogu
Gogu 2019년 7월 11일
Unfortunately, one rule for the second half of elements, are not met (1 move to b2) :
b1 =
2 1 1 1 0 1 1 1 0
b2 =
0 0 1 0 0 0 1 0 2
Gogu
Gogu 2019년 7월 12일
Solved !!!
lx = (length(b));
half = ceil(lx/2);
b1(1)=2;
b2(1)=0;
b1((n-1)^2)=0;
b2((n-1)^2)=2;
j=(n-1)^2;
for i=2:j-1
if b(i)==2
b1(i)=1;
b2(i)=1;
end
end
for i=2:half
if find(b(i)==1)
b1(i)=1;
b2(i)=0;
end
end
for i= half + 1 : j-1
if find(b(i)==1)
b1(i)=0;
b2(i)=1;
end
end
b1'
b2'

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Control System Toolbox에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by