I want to shift a part of a row vector to the right then adding a number before the shifted part

조회 수: 2 (최근 30일)
assuming I have
a=[1 2 3 4 0 0];
b=[0 0 1 0]
I want 'a' to be
a=[1 2 3 1.5 4 0]
the 1.5 is half the element before
and b indicates when does the shift occur

채택된 답변

Mehmed Saad
Mehmed Saad 2020년 5월 15일
편집: Mehmed Saad 2020년 5월 15일
if b contains only 1 shift
ind = find(b);
a(ind+1:end)=circshift(a(ind+1:end),1);
a(ind+1) = a(ind)/2;
a =
1.0000 2.0000 3.0000 1.5000 4.0000 0
  댓글 수: 4
Mohamed Salah
Mohamed Salah 2020년 5월 15일
a=[1 2 3 4 5 6 0 0 0 0]; %I always have number of zeros on the right equals the number of shifts
b=[1 1 1 1];
So 'a' should look like
a=[1, 0.5, 2, 1, 3, 1.5, 4, 2, 5, 2.5, 6]
'a' can be around 60 element and so is 'b'
Mehmed Saad
Mehmed Saad 2020년 5월 17일
편집: Mehmed Saad 2020년 5월 17일
Instead of padding zeros at the end of vector a use the following strategy
  1. Donot pad zeros at the end of a
  2. pad zeros in b such that length of a is equal to length of b
  3. replace all the zeros in b with NaN
  4. repeat a in 2nd dimension for example if a is [1 2] then after repeating it in 2nd dimension it will be [1 2;1 2]
  5. multiply 2nd row(repeated) with b and divide it by 2
  6. remove all the NaNs and remaining part will be your answer
a = [1 2 3 4 5 6];
b = [1 1 1 1];
b = [b zeros(1,length(a)-length(b))]; %Making a and b equal in length
b(b==0) = nan;% replacing all zeros in b with NaNs
a = repmat(a,2,1);% repeating the vector array across 2nd dimension
a(2,:) = (a(2,:).*b)/2;% multiplying 2nd row with b and dividing it by 2
a=a(~isnan(a))% index elements which are with out NaNs
The value of a will be
a =
1.0000 0.5000 2.0000 1.0000 3.0000 1.5000 4.0000 2.0000 5.0000 6.0000
similarly for
a = [ 1 2 3 4 0];
b = [0 1 0 0];
Result will be
a =
1.0000 2.0000 3.0000 1.5000 4.0000 0
Hope this works

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by