How do I make numbers shift left using function?

4 ビュー (過去 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 Center および File ExchangeIntroduction 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