how to shift rows to right and left of matrix ?

조회 수: 15 (최근 30일)
elor hdd
elor hdd 2021년 8월 21일
댓글: elor hdd 2021년 8월 21일
I want to shift the rows of the matrix to the right if A<B with shift step numbers c or left if A>B with shift step numbers c
v = [1,2 ,3;4,5,6;7,8,9];
[m,n]=size(v);
A=[3 2 1];
B=[2 5 2];
c=[4 1 3];%shift step number c
for i=1:m
for j=1:n
if A(i)<B(i) %shift row to right with shift step number c
p(i,j)=circshift(v(i,j),c(i),2)
else
p(i,j)=circshift(v(i,j),-c(i),2) %shift row to left with shift step number c
end
end
end

채택된 답변

Stephen23
Stephen23 2021년 8월 21일
M = [1,2,3;4,5,6;7,8,9]
M = 3×3
1 2 3 4 5 6 7 8 9
A = [3,2,1];
B = [2,5,2];
c = [4,1,3];
for k = 1:size(M,1)
if A(k)<B(k) %shift row to right with shift step number c
M(k,:) = circshift(M(k,:),c(k));
else %shift row to left with shift step number c
M(k,:) = circshift(M(k,:),-c(k));
end
end
M
M = 3×3
2 3 1 6 4 5 7 8 9

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품


릴리스

R2015a

Community Treasure Hunt

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

Start Hunting!

Translated by