フィルターのクリア

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

2 ビュー (過去 30 日間)
Amy Joyce Valencia
Amy Joyce Valencia 2021 年 10 月 29 日
回答済み: KSSV 2021 年 10 月 29 日
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

回答 (2 件)

Chunru
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
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 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
ans = logical
1
ans = logical
1
ans = logical
1
ans = logical
1
ans = logical
1

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by