How do I make numbers shift left using function?

4 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

C B
C B il 27 Ott 2021
Modificato: C B il 27 Ott 2021
@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 Commenti
Amy Joyce Valencia
Amy Joyce Valencia il 29 Ott 2021
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 il 29 Ott 2021
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

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Introduction to Installation and Licensing in Help Center e File Exchange

Prodotti


Release

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by