Filter löschen
Filter löschen

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

2 Ansichten (letzte 30 Tage)
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

Antworten (2)

Chunru
Chunru am 29 Okt. 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 am 29 Okt. 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

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by