How do I make numbers shift using a while loop while keeping the last itteration?
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/782653/image.png)
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
0 Commenti
Risposte (2)
Chunru
il 29 Ott 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
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
0 Commenti
KSSV
il 29 Ott 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
0 Commenti
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!