how to rotate integer vector from right to left and vis versa
조회 수: 4 (최근 30일)
이전 댓글 표시
Write afunction called rotleft that will receiveone row vector as an argument (you mayassume that it is a row vector with a length of at least two) and willreturn another vector, whichconsists of the input vector rotatedto the left—e.g., all values shift over one element, and the first element iswrapped around to theend. For example,
>> rotleft([1 3 4]) ans =
3 4 1
could anyone help please ?
댓글 수: 3
채택된 답변
DGM
2021년 11월 7일
Something like this
shamount = 1; % amount to shift left (negative to shift right)
A = 1:5 % test vector
B = circshift(A,[0 -shamount]) % using circshift
C = A(mod((1:numel(A))+shamount-1,numel(A))+1) % using basic indexing
댓글 수: 2
DGM
2021년 11월 8일
Pass parameters as input arguments instead of pestering the user for interactive inputs.
The result is assigned to a variable with the same name as the function instead of the output argument.
The rotation method doesn't do what you think it does. Consider:
vec = [12 15 20 17]
B = [20:-1:vec] % just creates a linear vector from 20 to vec(1)
I already mentioned ways to do this.
myvecrot(1:10,2)
myvecrot(1:10,-2)
function outvec = myvecrot(invec,k)
outvec = invec(mod((1:numel(invec))+k-1,numel(invec))+1);
end
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!