How do I make numbers shift left using function?

조회 수: 1 (최근 30일)
Amy Joyce Valencia
Amy Joyce Valencia 2021년 10월 27일
댓글: Amy Joyce Valencia 2021년 10월 29일
I have a function file that shifts the numbers to the left when called. But I dont know how to get it to loop so that it will keep shifting left.
function MyShiftLeft = MyShiftLeft(x)
y=[8 4 -2 5 4 0 -1]
temp=y(1); % save first value
% shift values left
for i=1:length(y)-1
y(i) = y(i+1);
end
% set last value to first
y(end)=temp;
y
When I use this code, it just keeps outputting the same one shifted matrix
n = input('Number of shifts to the left: ')
while n>0
MyShiftLeft
n-1
end

채택된 답변

C B
C B 2021년 10월 27일
편집: C B 2021년 10월 27일
@Amy Joyce Valencia I think this will work for you
function Output = MyShiftLeft(y,x)
for j=1:x
temp=y(1);
% shift values left
for i=1:length(y)-1
y(i) = y(i+1);
end
% set last value to first
y(end)=temp;
end
Output=y;
end
Here is the output
>> MyShiftLeft([8 4 -2 5 4 0 -1],1)
ans =
4 -2 5 4 0 -1 8
>> MyShiftLeft([8 4 -2 5 4 0 -1],2)
ans =
-2 5 4 0 -1 8 4
>> MyShiftLeft([8 4 -2 5 4 0 -1],3)
ans =
5 4 0 -1 8 4 -2
>> MyShiftLeft([8 4 -2 5 4 0 -1],4)
ans =
4 0 -1 8 4 -2 5
  댓글 수: 2
Amy Joyce Valencia
Amy Joyce Valencia 2021년 10월 29일
Is this the entire code? So I would just have to put the matrix in my regular code right? Not my function?
Amy Joyce Valencia
Amy Joyce Valencia 2021년 10월 29일
This is what my function file has looked like. I think it's the regular code I'm having a hard time with.
x = input('Number of shifts to the left: ');
y= [8 4 -2 5 4 0 -1];
while x>0
MyShiftLeft
x = x-1;
end

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by