How to move elements of vector

조회 수: 21 (최근 30일)
julie st cyr
julie st cyr 2020년 12월 10일
댓글: julie st cyr 2020년 12월 10일
How would I be able to find certain elements of a vector and move them?
For example, fidning the zeros in a vector and moving them to the right,
so [6 0 9 4; 0 4 0 6; 7 0 8 6; 4 5 0 9]
becomes [6 9 4 0; 4 6 0 0; 7 8 6 0; 4 5 9 0]
I have tried
vec = [vec(vec~=0) vec(vec==0)] but was unsuccessful.
Any help is appreciated thank you!
  댓글 수: 1
Fangjun Jiang
Fangjun Jiang 2020년 12월 10일
Because there are diffferent number of zeros in each row, I think you need to go through a for-loop, do it row by row should be relatively easy.

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

채택된 답변

James Tursa
James Tursa 2020년 12월 10일
편집: James Tursa 2020년 12월 10일
Could use a loop on the rows with logical indexing. E.g.,
vec = whatever
z = (vec == 0);
for r=1:size(vec,1)
vec(r,:) = [vec(r,~z(r,:)) vec(r,z(r,:))];
end
  댓글 수: 1
julie st cyr
julie st cyr 2020년 12월 10일
Just what I was looking for thank you so much!

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

추가 답변 (2개)

Ameer Hamza
Ameer Hamza 2020년 12월 10일
편집: Ameer Hamza 2020년 12월 10일
Try this
M = [6 0 9 4; 0 4 0 6; 7 0 8 6; 4 5 0 9];
[~, cols] = sort(M==0,2);
rows = repmat((1:size(M,1)).', 1, size(M,2));
M_new = M(sub2ind(size(M), rows, cols));
Result
>> M_new
M_new =
6 9 4 0
4 6 0 0
7 8 6 0
4 5 9 0

jessupj
jessupj 2020년 12월 10일
i can't think of how you might do this without a loop and maintain the matrix form. but your approach will work row-by-row
for k=1:size(vec,2);
vec(k,:) = [vec(k, vec(k,:)~=0) vec(k, vec(k,:)==0) ];
end

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by