How do I make numbers shift left using function?

2 次查看(过去 30 天)
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 中查找有关 Whos 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by