Borrar filtros
Borrar filtros

How do I make numbers shift using a while loop while keeping the last itteration?

2 visualizaciones (últimos 30 días)
I've made a separate function filed to call out the shift loop
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
And This is my regular code that calls the function
x = input('Number of shifts to the left: ');
while x>0
MyShiftLeft
x = x-1;
end
When I run it, instead of shifting the numbers however many times, it just duplicates the ouput
y =
8 4 -2 5 4 0 -1
y =
4 -2 5 4 0 -1 8
y =
8 4 -2 5 4 0 -1
y =
4 -2 5 4 0 -1 8

Respuestas (2)

Chunru
Chunru el 29 de Oct. de 2021
%x = input('Number of shifts to the left: ');
x = 3;
y=[8 4 -2 5 4 0 -1];
while x>0
y = MyShiftLeft(y)
x = x-1;
end
y = 1×7
4 -2 5 4 0 -1 8
y = 1×7
-2 5 4 0 -1 8 4
y = 1×7
5 4 0 -1 8 4 -2
function y = MyShiftLeft(y)
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;
end

KSSV
KSSV el 29 de Oct. de 2021
A = 1:5 ; % example array
for n = 1:5 % loop for shifting
B = circshift(A,n) ; % for comapring the answer use inbuilt function
% Code for shifting starts here
C = A ;
for i = 1:n
C = [C(end) C(1:end-1)] ;
end
isequal(C,B) % check he code and inbuiltin function
end
ans = logical
1
ans = logical
1
ans = logical
1
ans = logical
1
ans = logical
1

Categorías

Más información sobre Programming en Help Center y File Exchange.

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by