Effacer les filtres
Effacer les filtres

How do I make numbers shift left using function?

7 vues (au cours des 30 derniers jours)
Amy Joyce Valencia
Amy Joyce Valencia le 27 Oct 2021
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

Réponse acceptée

C B
C B le 27 Oct 2021
Modifié(e) : C B le 27 Oct 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 commentaires
Amy Joyce Valencia
Amy Joyce Valencia le 29 Oct 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 le 29 Oct 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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Introduction to Installation and Licensing dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by