How do I make numbers shift using a while loop while keeping the last itteration?
3 ビュー (過去 30 日間)
古いコメントを表示

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 件のコメント
回答 (2 件)
Chunru
2021 年 10 月 29 日
%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 件のコメント
KSSV
2021 年 10 月 29 日
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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Whos についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!