I want to shift vector values one by one to the left

Hello everyone,
I have a binary vector with five 0 and three 1.
num=[1 1 1 0 0 0 0 0]
and I want to shift each 1 left, shift one value as
num=[1 1 0 1 0 0 0 0]
untill I get a complete shift of the vector values and printing of each vector shift
num=[0 0 0 0 0 1 1 1]
any helpfull code of the above program with nested for loop will be highly appreciated
Thanks

댓글 수: 2

=> direction is on the right to my book.
PLEASE STOP POSTING MULTIPLE TIMES. You have posted the exact same question now three times. One I have now closed.

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

답변 (4개)

Chunru
Chunru 2022년 8월 30일
num=[1 1 1 0 0 0 0 0]
num = 1×8
1 1 1 0 0 0 0 0
for i=1:3
num = circshift(num, -1)
end
num = 1×8
1 1 0 0 0 0 0 1
num = 1×8
1 0 0 0 0 0 1 1
num = 1×8
0 0 0 0 0 1 1 1
What about this:
num = [1 1 1 1 1 0 0 0 0 0] ;
for ii = 1: nnz(num)
num = circshift(num, -1)
end
num = 1×10
1 1 1 1 0 0 0 0 0 1
num = 1×10
1 1 1 0 0 0 0 0 1 1
num = 1×10
1 1 0 0 0 0 0 1 1 1
num = 1×10
1 0 0 0 0 0 1 1 1 1
num = 1×10
0 0 0 0 0 1 1 1 1 1

댓글 수: 4

Thank you for your reply, but we need to use for loop as circular shift doesnot meet our random data vectors, eg if our vector is
num = [1 1 0 1 0 1 0 1 0 0]
then using circular shift will not move 1s to left and zeros to right, we need to shift every 1 on the left most side
num = [1 1 0 1 0 1 0 0 0 1]
num = [1 1 0 1 0 0 0 0 1 1]
num = [1 1 0 0 0 0 0 1 1 1]
num = [1 0 0 0 0 0 1 1 1 1]
num = [0 0 0 0 0 1 1 1 1 1]
like this. thanks in advance
Do you get a rule of shifting data?
I already had an idea of shifting but it does not fullfill the requirement that i want.
if you only need the last vector,then use sort function.
sort(yourVectorHere)

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

Bruno Luong
Bruno Luong 2022년 8월 30일
편집: Bruno Luong 2022년 8월 30일
Is it what you want?
num = [1 1 0 1 0 1 0 1 0 0];
j = find(num);
m = length(j);
l = (-m+1:0)+(length(num))-j;
q = sum(l)+1;
J = zeros(q,m);
i = 1;
J(i,:) = j;
for k=m:-1:1
for n=1:l(k)
i = i+1;
j(k) = j(k)+1;
J(i,:) = j;
end
end
I = repmat((1:q)',1,m);
B = accumarray([I(:) J(:)],1)
B = 20×10
1 1 0 1 0 1 0 1 0 0 1 1 0 1 0 1 0 0 1 0 1 1 0 1 0 1 0 0 0 1 1 1 0 1 0 0 1 0 0 1 1 1 0 1 0 0 0 1 0 1 1 1 0 1 0 0 0 0 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 0 0 1 0 0 1 1 1 1 0 0 0 0 1 0 1 1 1 1 0 0 0 0 0 1 1 1
May be this?
num = [1 1 0 1 0 1 0 1 0 0];
j = find(num);
m = length(j);
J=repmat(j,m,1);
for i=m:-1:1
J(m-i+1:end,i) = length(num)+i-m;
end
J = [j; J];
I = repmat((1:m+1)',1,m);
B = accumarray([I(:) J(:)],1)
B = 6×10
1 1 0 1 0 1 0 1 0 0 1 1 0 1 0 1 0 0 0 1 1 1 0 1 0 0 0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 1

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2022년 8월 30일

답변:

2022년 8월 30일

Community Treasure Hunt

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

Start Hunting!

Translated by