I have an array and i want to to move the element a which located in x line, by one position to the right without change the left part

댓글 수: 3

Guillaume
Guillaume 2017년 9월 5일
Can you provide an example of before and after?
GEORGIOS KOULIDIS
GEORGIOS KOULIDIS 2017년 9월 5일
편집: Stephen23 2017년 9월 6일
I have the array
A=[ 1 2 3 4 0 0 0;
5 3 2 1 0 0 0]
and i want to do that
A=[ 1 2 3 4 0 0 0;
5 3 0 2 1 0 0]
If you have this as original array:
A=[ 1 2 3 4 0 0 0;
5 3 2 1 0 0 0;
4 4 4 4 0 0 0;
2 3 4 5 6 7 8]
You want to move the elements starting from line row=2, column=3 (this is your number two), and replace the element originally in position row=2 column=3 by another element stored in the variable replacewith (in this case 0), then write:
A=[ 1 2 3 4 0 0 0;
5 3 2 1 0 0 0;
4 4 4 4 0 0 0;
2 3 4 5 6 7 8]
x=2
y=3
replacewith=0;
result_xth_row=[A(x,1:y-1),replacewith,A(x,y:end-1)]
A(x,1:end)=result_xth_row
A

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

 채택된 답변

Cam Salzberger
Cam Salzberger 2017년 9월 5일

0 개 추천

Hello Georgios,
I'm not sure what the absolute best way to do this for your particular application, but here is one way you could do it.
A = [1 2 3 4 0 0 0 ; 5 3 2 1 0 0 0];
Aorig = A;
A(2,4:5) = Aorig(2,3:4);
A(2,3) = Aorig(2,5);
Or if you'd rather one-line it:
A(2,3:5) = A(2,[5 3 4]);
I'll let you work out a more general function though, depending on what you know, and what you'll need to adapt for as an input.
-Cam

댓글 수: 2

GEORGIOS KOULIDIS
GEORGIOS KOULIDIS 2017년 9월 5일
can you give me a general answer please ?
Like I said, I don't know why you are trying to do this, so I don't know what the general case is. If you are always going to be moving two values on the second row of the matrix to one earlier position, it could be as simple as:
function A = shiftTwoVals(A,iCol)
A(2,[iCol-1:iCol+1]) = A(2,[iCol+1 iCol-1 iCol]);
end
If you just want a general case of swapping any elements with any other elements in the matrix, then you are better off learning what I did with the indexing, since that is the best way. On the left side of the equals sign, the indices of the matrix tell it which positions are going to be modified. On the right side of the equals sign, the indices of the matrix tell it which values to use.
It can be simpler to visualize if you index linearly rather than with row and column values.

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

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2017년 9월 5일

0 개 추천

A(2,3:end) = circshift(A(2,3:end),1)

댓글 수: 1

GEORGIOS KOULIDIS
GEORGIOS KOULIDIS 2017년 9월 5일
it doesnot run It show me this message : Warning: CIRCSHIFT(X,K) with scalar K and where size(X,1)==1 will change behavior in future versions. To retain current behavior, use CIRCSHIFT(X,[K,0]) instead.

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

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

질문:

2017년 9월 5일

댓글:

2017년 9월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by